Сделаны переводы другим пользователям

This commit is contained in:
AidarKC
2026-11-18 12:07:13 +03:00
parent fc86c6190e
commit 780ca53931
19 changed files with 1387 additions and 215 deletions
+26 -155
View File
@@ -1292,21 +1292,6 @@ function renderLog(
);
}
bubble.append(attachmentsWrap);
const expiresAt = dmAttachments
.filter((item) => Number(item?.version || 1) >= 3)
.map((item) => Number(item.uploadedAtMs || msg?.timeMs || 0) + 14 * 24 * 60 * 60 * 1000)
.filter((value) => value > 14 * 24 * 60 * 60 * 1000);
if (expiresAt.length) {
const remaining = Math.min(...expiresAt) - Date.now();
const expiry = document.createElement('div');
expiry.className = 'dm-attachment-expiry';
expiry.textContent = remaining <= 0
? t('screens.dm_attachments.file_expired_short')
: remaining < 24 * 60 * 60 * 1000
? t('screens.dm_attachments.remaining_less_day')
: t('screens.dm_attachments.remaining_days', { value1: Math.ceil(remaining / (24 * 60 * 60 * 1000)) });
bubble.append(expiry);
}
}
const textNode = document.createElement('div');
@@ -1579,7 +1564,7 @@ export function render({ navigate, route, chrome }) {
onClick: () => handleStartCall('video'),
},
{
iconNode: createOverflowDots(),
iconNode: createOverflowDots({ className: 'app-overflow-dots--vertical' }),
title: t('screens.chat_view.text_013'),
ariaLabel: t('screens.chat_view.text_014'),
className: 'chat-header-icon-btn chat-header-menu-btn topbar-overflow-action--raised',
@@ -1605,6 +1590,7 @@ export function render({ navigate, route, chrome }) {
},
}
: null,
{ label: t('wallet_multi.transfer_to_contact'), iconHtml: menuIconSvg('forward'), action: () => navigate(`wallet/transfer/${encodeURIComponent(chatId)}`) },
{ divider: true },
{
label: t('screens.chat_view.text_020'),
@@ -1912,11 +1898,9 @@ export function render({ navigate, route, chrome }) {
<button class="dm-bar-icon dm-camera-btn" type="button" id="chat-camera-toggle" aria-label="${th('screens.chat_view.text_115')}" title="${th('screens.chat_view.text_116')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('camera')}</button>
<button class="dm-bar-icon dm-file-btn" type="button" id="chat-file-toggle" aria-label="${th('screens.chat_view.text_117')}" title="${th('screens.chat_view.text_118')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('clip')}</button>
<div class="dm-voice-recording-status" id="chat-voice-recording-status" hidden>
<button class="dm-voice-cancel" type="button" id="chat-voice-cancel" aria-label="${th('screens.chat_view.voice_cancel')}">✕</button>
<span class="dm-voice-recording-dot" aria-hidden="true"></span>
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</span>
<span class="dm-voice-recording-hint" id="chat-voice-recording-hint">${th('screens.chat_view.text_119')}</span>
<button class="dm-voice-pause" type="button" id="chat-voice-pause" hidden></button>
</div>
<div class="dm-field">
<textarea class="input dm-input" name="message" rows="1" placeholder="${th('screens.chat_view.text_120')}" maxlength="12000" enterkeyhint="enter"></textarea>
@@ -1924,7 +1908,6 @@ export function render({ navigate, route, chrome }) {
<button class="dm-bar-icon dm-emoji-btn" type="button" id="chat-emoji-toggle" aria-label="${th('screens.chat_view.text_121')}" title="${th('screens.chat_view.text_122')}">${iconHtml('emoji')}</button>
<button class="dm-send-btn dm-send-icon-btn" type="button" title="${th('screens.chat_view.text_123')}" data-mode="voice" aria-label="${th('screens.chat_view.text_124')}"></button>
</div>
<div class="dm-file-queue" id="chat-file-queue" hidden></div>
<input id="chat-file-input" type="file" multiple hidden />
<input id="chat-media-input" type="file" accept="image/*,video/*" multiple hidden />
<input id="chat-camera-input" type="file" accept="image/*,video/*" capture="environment" hidden />
@@ -1935,7 +1918,6 @@ export function render({ navigate, route, chrome }) {
const emojiToggle = form.querySelector('#chat-emoji-toggle');
const fileToggle = form.querySelector('#chat-file-toggle');
const fileInput = form.querySelector('#chat-file-input');
const fileQueue = form.querySelector('#chat-file-queue');
// Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один.
const attachSources = [
[fileToggle, fileInput],
@@ -1947,8 +1929,6 @@ export function render({ navigate, route, chrome }) {
const voiceStatus = form.querySelector('#chat-voice-recording-status');
const voiceTime = form.querySelector('#chat-voice-recording-time');
const voiceHint = form.querySelector('#chat-voice-recording-hint');
const voicePause = form.querySelector('#chat-voice-pause');
const voiceCancel = form.querySelector('#chat-voice-cancel');
const fileTransferEnabled = isDmFileTransferEnabled();
const editBanner = form.querySelector('#chat-edit-banner');
const editBannerText = form.querySelector('#chat-edit-banner-text');
@@ -1961,8 +1941,6 @@ export function render({ navigate, route, chrome }) {
let emojiLongPressTimer = null;
let emojiLongPressTriggered = false;
let fileActionVisible = false;
let queuedFiles = [];
let fileSending = false;
let voiceRecorder = null;
let voiceStream = null;
let voiceChunks = [];
@@ -1972,11 +1950,6 @@ export function render({ navigate, route, chrome }) {
let voicePointerHeld = false;
let voiceReleaseRequested = false;
let voiceStartY = 0;
let voiceStartX = 0;
let voicePressStartedAt = 0;
let voiceCancelRequested = false;
let voicePausedMs = 0;
let voicePausedAt = 0;
let voicePointerId = null;
let voiceBusy = false;
let suppressVoiceClick = false;
@@ -2052,7 +2025,7 @@ export function render({ navigate, route, chrome }) {
return iconHtml('send');
}
if (mode === 'stop') {
return iconHtml('send');
return '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></svg>';
}
if (mode === 'busy') {
return '<span class="dm-send-busy-dot">…</span>';
@@ -2060,8 +2033,7 @@ export function render({ navigate, route, chrome }) {
return iconHtml('mic');
};
const currentVoiceDurationMs = () => voiceStartedAt > 0
? Math.max(0, (voicePausedAt || Date.now()) - voiceStartedAt - voicePausedMs) : 0;
const currentVoiceDurationMs = () => voiceStartedAt > 0 ? Math.max(0, Date.now() - voiceStartedAt) : 0;
const syncVoiceTimer = () => {
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
@@ -2087,22 +2059,22 @@ export function render({ navigate, route, chrome }) {
if (!sendBtn) return;
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
let mode = 'voice';
if (voiceBusy || fileSending) mode = 'busy';
if (voiceBusy) mode = 'busy';
else if (recording && voiceLocked) mode = 'stop';
else if (recording) mode = 'voice';
else if (activeEdit || queuedFiles.length || String(input?.value || '').trim()) mode = 'send';
else if (activeEdit || String(input?.value || '').trim()) mode = 'send';
sendBtn.dataset.mode = mode;
sendBtn.innerHTML = sendIconMarkup(mode);
sendBtn.classList.toggle('is-recording', recording);
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
sendBtn.disabled = voiceBusy || fileSending || (mode === 'voice' && !recording && !fileTransferEnabled);
sendBtn.disabled = voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
if (mode === 'send') {
sendBtn.title = t('screens.chat_view.text_029');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
} else if (mode === 'stop') {
sendBtn.title = t('screens.chat_view.voice_send');
sendBtn.setAttribute('aria-label', t('screens.chat_view.voice_send'));
sendBtn.title = t('screens.chat_view.text_030');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
} else if (mode === 'busy') {
sendBtn.title = t('screens.chat_view.text_031');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_031'));
@@ -2112,13 +2084,6 @@ export function render({ navigate, route, chrome }) {
}
form.classList.toggle('dm-chat-input--recording', recording);
if (voiceStatus) voiceStatus.hidden = !recording;
if (voicePause) {
voicePause.hidden = !recording || !voiceLocked;
voicePause.textContent = voiceRecorder?.state === 'paused' ? '▶' : 'Ⅱ';
voicePause.setAttribute('aria-label', t(voiceRecorder?.state === 'paused' ? 'screens.chat_view.voice_resume' : 'screens.chat_view.voice_pause'));
}
form.classList.toggle('dm-chat-input--voice-locked', recording && voiceLocked);
form.classList.toggle('dm-chat-input--voice-paused', recording && voiceRecorder?.state === 'paused');
if (input) input.hidden = recording;
if (emojiToggle) emojiToggle.hidden = recording;
attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; });
@@ -2146,10 +2111,7 @@ export function render({ navigate, route, chrome }) {
const stopVoiceRecording = ({ send = true } = {}) => {
voicePointerHeld = false;
voiceReleaseRequested = true;
if (!voiceRecorder || voiceRecorder.state === 'inactive') {
if (!send) voiceCancelRequested = true;
return;
}
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
voiceRecorder.__shineShouldSend = Boolean(send);
try {
voiceRecorder.stop();
@@ -2158,7 +2120,7 @@ export function render({ navigate, route, chrome }) {
}
};
const startVoiceRecording = async ({ pointerY = 0, pointerX = 0, pointerId = null } = {}) => {
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
@@ -2177,11 +2139,7 @@ export function render({ navigate, route, chrome }) {
voiceReleaseRequested = false;
voiceLocked = false;
voiceStartY = Number(pointerY || 0);
voiceStartX = Number(pointerX || 0);
voicePointerId = pointerId;
voiceCancelRequested = false;
voicePausedMs = 0;
voicePausedAt = 0;
suppressVoiceClick = false;
try {
@@ -2209,15 +2167,13 @@ export function render({ navigate, route, chrome }) {
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
});
recorder.addEventListener('stop', async () => {
const shouldSend = recorder.__shineShouldSend !== false && !voiceCancelRequested;
const shouldSend = recorder.__shineShouldSend !== false;
const durationMs = currentVoiceDurationMs();
const chunks = voiceChunks.slice();
voiceChunks = [];
voiceRecorder = null;
voiceLocked = false;
voiceStartedAt = 0;
voicePausedAt = 0;
voicePausedMs = 0;
clearVoiceTimer();
stopVoiceStreamTracks();
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
@@ -2256,8 +2212,7 @@ export function render({ navigate, route, chrome }) {
recorder.start(1000);
voiceTimer = window.setInterval(syncVoiceTimer, 250);
updateSendButtonMode();
if (voiceCancelRequested) stopVoiceRecording({ send: false });
else if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
} catch (error) {
voicePointerHeld = false;
voiceReleaseRequested = false;
@@ -2573,7 +2528,7 @@ export function render({ navigate, route, chrome }) {
}
};
const sendFileAttachmentMessage = async (attachmentsInput, caption = '') => {
const sendFileAttachmentMessage = async (attachmentsInput) => {
const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
if (!attachments.length) return;
if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
@@ -2588,7 +2543,7 @@ export function render({ navigate, route, chrome }) {
: (attachments.length === 1
? `📎 ${String(attachments[0]?.name || 'file')}`
: t('screens.chat_view.text_097', { value1: attachments.length }));
const finalText = `${replyBlock}${fileBlocks}${String(caption || '').trim() || fallbackText}`;
const finalText = `${replyBlock}${fileBlocks}${fallbackText}`;
hideUnreadSeparator({ rerender: false });
const tempId = addOutgoingPendingMessage(chatId, finalText);
@@ -2652,7 +2607,7 @@ export function render({ navigate, route, chrome }) {
};
// Файлы уже лежат на сервере – повторить можно одно сообщение с ключами, без новой загрузки.
const offerAttachmentsRetry = (attachments, error, caption = '') => {
const offerAttachmentsRetry = (attachments, error) => {
showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
kind: 'error',
action: {
@@ -2660,40 +2615,17 @@ export function render({ navigate, route, chrome }) {
onClick: async () => {
if (disposed) return;
try {
await sendFileAttachmentMessage(attachments, caption);
await sendFileAttachmentMessage(attachments);
if (!disposed) showToast(attachments.length === 1 ? t('screens.chat_view.text_077') : t('screens.chat_view.text_100', { value1: attachments.length }), { timeoutMs: 1300 });
} catch (again) {
if (!disposed) offerAttachmentsRetry(attachments, again, caption);
if (!disposed) offerAttachmentsRetry(attachments, again);
}
},
},
});
};
const renderQueuedFiles = () => {
fileQueue.replaceChildren();
fileQueue.hidden = !queuedFiles.length;
queuedFiles.forEach((file, index) => {
const chip = document.createElement('span');
chip.className = 'dm-file-queue__chip';
const name = document.createElement('span');
name.textContent = file.name;
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '✕';
remove.setAttribute('aria-label', t('screens.chat_view.file_remove', { value1: file.name }));
remove.addEventListener('click', () => {
queuedFiles.splice(index, 1);
renderQueuedFiles();
});
chip.append(name, remove);
fileQueue.append(chip);
});
updateSendButtonMode();
};
const handleSelectedFiles = async (fileList) => {
if (fileSending) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
return;
@@ -2703,14 +2635,11 @@ export function render({ navigate, route, chrome }) {
return;
}
const allFiles = Array.from(fileList || []).filter(Boolean);
const caption = String(input?.value || '').trim();
if (!allFiles.length) return;
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
return;
}
fileSending = true;
updateSendButtonMode();
attachButtons.forEach((button) => {
button.disabled = true;
@@ -2738,26 +2667,13 @@ export function render({ navigate, route, chrome }) {
attachments.push(attachment);
}
uploaded = true;
await sendFileAttachmentMessage(attachments, caption);
queuedFiles = [];
renderQueuedFiles();
if (caption && String(input?.value || '').trim() === caption) {
input.value = '';
autoResizeComposer(input);
updateSendButtonMode();
}
await sendFileAttachmentMessage(attachments);
setFileActionVisible(false);
showToast(attachments.length === 1 ? t('screens.chat_view.text_078') : t('screens.chat_view.text_103', { value1: attachments.length }), { timeoutMs: 1300 });
} catch (error) {
if (uploaded) {
queuedFiles = [];
renderQueuedFiles();
offerAttachmentsRetry(attachments, error, caption);
}
if (uploaded) offerAttachmentsRetry(attachments, error);
else showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
} finally {
fileSending = false;
updateSendButtonMode();
attachButtons.forEach((button) => {
button.disabled = false;
button.classList.remove('is-busy');
@@ -3005,14 +2921,7 @@ export function render({ navigate, route, chrome }) {
});
picker?.addEventListener('change', () => {
const files = Array.from(picker.files || []);
if (!files.length) return;
if (queuedFiles.length + files.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error' });
return;
}
queuedFiles.push(...files);
renderQueuedFiles();
picker.value = '';
if (files.length) void handleSelectedFiles(files);
});
});
screen.addEventListener('pointerdown', (event) => {
@@ -3045,21 +2954,14 @@ export function render({ navigate, route, chrome }) {
voicePointerHeld = true;
voiceReleaseRequested = false;
voiceStartY = Number(event.clientY || 0);
voicePressStartedAt = Date.now();
voicePointerId = event.pointerId;
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ }
void startVoiceRecording({ pointerY: voiceStartY, pointerX: event.clientX, pointerId: event.pointerId });
void startVoiceRecording({ pointerY: voiceStartY, pointerId: event.pointerId });
});
sendBtn?.addEventListener('pointermove', (event) => {
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return;
if (Number(event.clientX || 0) <= voiceStartX - 72) {
voiceCancelRequested = true;
suppressVoiceClick = true;
stopVoiceRecording({ send: false });
if (voiceHint) voiceHint.textContent = t('screens.chat_view.voice_cancelled');
return;
}
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
if (Number(event.clientY || 0) <= voiceStartY - 64) {
voiceLocked = true;
voiceReleaseRequested = false;
@@ -3076,40 +2978,13 @@ export function render({ navigate, route, chrome }) {
voiceReleaseRequested = true;
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
voicePointerId = null;
if (!voiceLocked && !voiceCancelRequested && Date.now() - voicePressStartedAt < 350) {
voiceLocked = true;
voiceReleaseRequested = false;
if (voiceHint) voiceHint.textContent = t('screens.chat_view.voice_tap_hint');
updateSendButtonMode();
if (!voiceLocked) {
suppressVoiceClick = true;
} else if (!voiceLocked) {
suppressVoiceClick = true;
stopVoiceRecording({ send: !voiceCancelRequested });
stopVoiceRecording({ send: true });
}
};
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture);
sendBtn?.addEventListener('pointercancel', (event) => {
if (voicePointerId !== event.pointerId) return;
voiceCancelRequested = true;
finishVoicePointerGesture(event);
stopVoiceRecording({ send: false });
});
voiceCancel?.addEventListener('click', () => {
voiceCancelRequested = true;
stopVoiceRecording({ send: false });
});
voicePause?.addEventListener('click', () => {
if (!voiceRecorder || !voiceLocked) return;
if (voiceRecorder.state === 'recording') {
voiceRecorder.pause();
voicePausedAt = Date.now();
} else if (voiceRecorder.state === 'paused') {
voicePausedMs += Date.now() - voicePausedAt;
voicePausedAt = 0;
voiceRecorder.resume();
}
updateSendButtonMode();
});
sendBtn?.addEventListener('pointercancel', finishVoicePointerGesture);
sendBtn?.addEventListener('contextmenu', (event) => {
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
});
@@ -3138,10 +3013,6 @@ export function render({ navigate, route, chrome }) {
form.addEventListener('submit', async (event) => {
event.preventDefault();
const text = String(input.value || '').trim();
if (queuedFiles.length) {
await handleSelectedFiles(queuedFiles);
return;
}
if (!text) return;
input.value = '';
autoResizeComposer(input);
+194
View File
@@ -0,0 +1,194 @@
/** SHiNE wallet beta swap — in-app Jupiter routing, user's blockchainKey signs locally. */
import { createTopBar } from '../components/topbar.js';
import { state } from '../state.js';
import { t } from '../i18n/index.js';
import { getBalanceSol, getWalletFromStoredBlockchainKey } from '../services/solana-wallet-service.js';
import { getUsdtBalance, formatAtomicAmount } from '../services/solana-usdt-service.js';
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
import { requestSwapBuild, validateSwapInput, validateSwapBuildResponse, executeJupiterSwap, getPendingSwapSignature } from '../services/jupiter-swap-service.js';
export const pageMeta = { id: 'wallet-swap-view', get title() { return t('wallet_swap.title'); } };
export function render({ navigate, chrome }) {
chrome?.setTopbar(createTopBar({ title: t('wallet_swap.title'), back: { label: '←', onClick: () => navigate('wallet') } }));
const screen = document.createElement('section');
screen.className = 'stack wallet-transfer-screen wallet-swap-screen';
const card = document.createElement('div');
card.className = 'card stack wallet-transfer-card wallet-swap-card';
card.innerHTML = `
<h2 data-heading></h2>
<p class="wallet-swap-beta-tag" data-beta></p>
<p class="wallet-swap-warning" data-warning></p>
<div class="wallet-transfer-balances">
<div class="wallet-transfer-balance"><span>SOL</span><strong data-balance-sol>—</strong></div>
<div class="wallet-transfer-balance"><span>USDT</span><strong data-balance-usdt>—</strong></div>
</div>
<label class="wallet-transfer-field"><span data-from-label></span><select class="input wallet-transfer-select" data-from><option value="SOL">SOL → USDT</option><option value="USDT">USDT → SOL</option></select></label>
<label class="wallet-transfer-field"><span data-amount-label></span><input class="input" inputmode="decimal" autocomplete="off" data-amount type="text" placeholder="0.01" /></label>
<p class="meta-muted wallet-swap-limit" data-limit></p>
<button type="button" class="secondary-btn wallet-swap-quote-button" data-quote></button>
<div class="wallet-swap-quote-box" data-preview hidden>
<div><span data-receive-label></span><strong data-receive>—</strong></div>
<div><span data-min-label></span><strong data-min>—</strong></div>
<div><span data-route-label></span><strong>Jupiter Metis</strong></div>
<p class="meta-muted" data-preview-hint></p>
</div>
<label class="wallet-transfer-notice wallet-swap-consent" data-consent-row hidden><input type="checkbox" data-consent /><span data-consent-label></span></label>
<button type="button" class="primary-btn wallet-swap-confirm" data-confirm hidden disabled></button>
<p class="meta-muted wallet-transfer-status" data-status role="status" aria-live="polite"></p>
<a data-explorer target="_blank" rel="noopener noreferrer" class="wallet-swap-explorer" hidden></a>
<button type="button" class="secondary-btn wallet-swap-check" data-check hidden></button>
`;
const el = (name) => card.querySelector(`[data-${name}]`);
el('heading').textContent = t('wallet_swap.title');
el('beta').textContent = t('wallet_swap.beta');
el('warning').textContent = t('wallet_swap.warning');
el('from-label').textContent = t('wallet_swap.direction');
el('amount-label').textContent = t('wallet_swap.amount');
el('quote').textContent = t('wallet_swap.get_quote');
el('receive-label').textContent = t('wallet_swap.expected');
el('min-label').textContent = t('wallet_swap.minimum');
el('route-label').textContent = t('wallet_swap.route');
el('preview-hint').textContent = t('wallet_swap.quote_note');
el('consent-label').textContent = t('wallet_swap.accept_risk');
el('confirm').textContent = t('wallet_swap.execute');
el('check').textContent = t('wallet_swap.check_status');
screen.append(card);
const mainnet = getSolanaCluster() === 'mainnet-beta';
const endpoint = state.entrySettings.solanaServer;
let destroyed = false;
let busy = false;
let walletAddress = '';
let balances = { solLamports: null, usdtAtomic: null };
let lastQuote = null;
let lastAmount = '';
let lastCurrency = '';
let blocked = false;
const status = (s) => { if (!destroyed) el('status').textContent = s || ''; };
const showExplorer = (signature) => {
const link = el('explorer');
if (!signature || !/^[1-9A-HJ-NP-Za-km-z]{80,100}$/.test(signature)) { link.hidden = true; return; }
link.href = `https://solscan.io/tx/${encodeURIComponent(signature)}`;
link.textContent = `${t('wallet_swap.transaction')}: ${signature}`;
link.hidden = false;
};
const resetQuote = () => {
lastQuote = null;
el('preview').hidden = true;
el('consent-row').hidden = true;
el('consent').checked = false;
el('confirm').hidden = true;
el('confirm').disabled = true;
};
const setBusy = (value) => {
busy = value;
el('amount').disabled = value || !mainnet;
el('from').disabled = value || !mainnet;
el('quote').disabled = value || !mainnet || blocked;
el('confirm').disabled = value || !lastQuote || blocked || !el('consent').checked;
};
const updateLimit = () => {
el('limit').textContent = el('from').value === 'SOL' ? t('wallet_swap.sol_limit') : t('wallet_swap.usdt_limit');
resetQuote();
};
el('from').addEventListener('change', updateLimit);
el('amount').addEventListener('input', resetQuote);
el('consent').addEventListener('change', () => { el('confirm').disabled = !el('consent').checked || blocked || busy; });
updateLimit();
async function refreshBalances() {
const login = state.session.login;
const storagePwd = state.session.storagePwdInMemory;
if (!login || !storagePwd) throw new Error(t('wallet_swap.session_required'));
const wallet = await getWalletFromStoredBlockchainKey({ login, storagePwd });
walletAddress = wallet.address;
const [sol, usdt] = await Promise.all([getBalanceSol({ endpoint, address: walletAddress }), getUsdtBalance({ endpoint, address: walletAddress })]);
if (destroyed) return;
balances = { solLamports: BigInt(sol.lamports), usdtAtomic: usdt.atomic };
el('balance-sol').textContent = `${sol.sol.toFixed(6)} SOL`;
el('balance-usdt').textContent = `${usdt.text} USDT`;
}
async function checkPrevious() {
const pending = await getPendingSwapSignature(endpoint);
if (destroyed) return;
const wasBlocked = blocked;
blocked = Boolean(pending);
el('check').hidden = !pending;
if (pending) {
status(t('wallet_swap.pending'));
showExplorer(pending);
} else if (wasBlocked) {
status(t('wallet_swap.pending_resolved'));
}
setBusy(false);
}
el('check').addEventListener('click', () => { void checkPrevious().catch((error) => status(error.message || String(error))); });
if (!mainnet) {
status(t('wallet_swap.devnet_unavailable'));
setBusy(false);
} else {
void (async () => {
try { await refreshBalances(); await checkPrevious(); }
catch (error) { status(error.message || String(error)); }
})();
}
el('quote').addEventListener('click', async () => {
if (busy || destroyed || blocked || !mainnet) return;
resetQuote();
showExplorer('');
try {
const { pair, amount } = validateSwapInput(el('from').value, el('amount').value, balances);
setBusy(true);
status(t('wallet_swap.fetching'));
if (!walletAddress) throw new Error(t('wallet_swap.session_required'));
const prepared = await requestSwapBuild({ inputCurrency: pair.inputCurrency, amountAtomic: amount, walletAddress });
if (destroyed) return;
const checked = validateSwapBuildResponse(prepared.response, pair, amount);
lastQuote = prepared;
lastAmount = el('amount').value;
lastCurrency = el('from').value;
el('receive').textContent = `${formatAtomicAmount(checked.expected, pair.outputDecimals)} ${pair.outputCurrency}`;
el('min').textContent = `${formatAtomicAmount(checked.minimum, pair.outputDecimals)} ${pair.outputCurrency}`;
el('preview').hidden = false;
el('consent-row').hidden = false;
el('confirm').hidden = false;
status(t('wallet_swap.review'));
} catch (error) { status(error.message || String(error)); }
finally { if (!destroyed) setBusy(false); }
});
el('confirm').addEventListener('click', async () => {
if (busy || blocked || !lastQuote || !el('consent').checked || destroyed) return;
if (lastCurrency !== el('from').value || lastAmount !== el('amount').value) { resetQuote(); return; }
if (Date.now() - lastQuote.fetchedAt > 30_000) { resetQuote(); status(t('wallet_swap.stale')); return; }
const checked = validateSwapBuildResponse(lastQuote.response, lastQuote.pair, lastQuote.amount);
const info = `${formatAtomicAmount(lastQuote.amount, lastQuote.pair.inputDecimals)} ${lastQuote.pair.inputCurrency} → ${formatAtomicAmount(checked.expected, lastQuote.pair.outputDecimals)} ${lastQuote.pair.outputCurrency}\n${t('wallet_swap.minimum')}: ${formatAtomicAmount(checked.minimum, lastQuote.pair.outputDecimals)} ${lastQuote.pair.outputCurrency}`;
if (!window.confirm(`${t('wallet_swap.final_warning')}\n\n${info}\n\n${t('wallet_swap.final_question')}`)) return;
const confirmedQuote = lastQuote;
resetQuote(); // One-shot, even if signing or RPC fails.
setBusy(true);
status(t('wallet_swap.executing'));
try {
if (await getPendingSwapSignature(endpoint)) throw new Error(t('wallet_swap.pending'));
const wallet = await getWalletFromStoredBlockchainKey({ login: state.session.login, storagePwd: state.session.storagePwdInMemory });
if (wallet.address !== walletAddress) throw new Error(t('wallet_swap.wallet_changed'));
const result = await executeJupiterSwap({ endpoint, fromKeypair: wallet.keypair, prepared: confirmedQuote });
if (!destroyed) {
showExplorer(result.signature);
blocked = true; // No one-click repeat from this page after success.
status(t('wallet_swap.success'));
await refreshBalances();
}
} catch (error) {
if (!destroyed) {
status(error.message || String(error));
if (error.signature) { blocked = true; showExplorer(error.signature); el('check').hidden = false; }
}
} finally { if (!destroyed) setBusy(false); }
});
screen.cleanup = () => { destroyed = true; };
return screen;
}
+213
View File
@@ -0,0 +1,213 @@
/** One dedicated transfer screen, opened from Wallet or an existing DM contact. */
import { createTopBar } from '../components/topbar.js';
import { authService, state } from '../state.js';
import { getBalanceSol, getWalletFromStoredBlockchainKey, transferSolLamports, solanaAddressFromPublicKeyBase64 } from '../services/solana-wallet-service.js';
import { getUsdtAsset, getUsdtBalance, toAtomicAmount, formatAtomicAmount, transferUsdt } from '../services/solana-usdt-service.js';
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
import { readShineUserPda } from '../services/shine-user-pda-service.js';
import { bytesToBase58 } from '../services/crypto-utils.js';
import { t } from '../i18n/index.js';
export const pageMeta = { id: 'wallet-transfer-view', get title() { return t('wallet_multi.transfer_title'); } };
/** Use the blockchain public key, never clientKey (DM) or rootKey. */
export async function resolveContactBlockchainAddress(login, endpoint) {
const cleanLogin = String(login || '').trim();
if (!cleanLogin) throw new Error('Не указан получатель');
try {
const pda = await readShineUserPda({ login: cleanLogin, solanaEndpoint: endpoint });
const latest = pda?.forks?.at(-1)?.blockchainKey;
if (latest?.length === 32) return bytesToBase58(latest);
} catch { /* A Free account may not have a paid Solana PDA. */ }
const user = await authService.getUser(cleanLogin);
if (!user?.exists || !user.blockchainKey) throw new Error('Не удалось получить blockchainKey получателя');
return solanaAddressFromPublicKeyBase64(user.blockchainKey);
}
export function render({ navigate, chrome, route }) {
const recipientFromRoute = String(route?.params?.recipientLogin || '').trim();
const backTarget = recipientFromRoute ? `chat/${encodeURIComponent(recipientFromRoute)}` : 'wallet';
chrome?.setTopbar(createTopBar({
title: t('wallet_multi.transfer_title'),
back: { label: '←', onClick: () => navigate(backTarget) },
}));
const screen = document.createElement('section');
screen.className = 'stack wallet-transfer-screen';
const card = document.createElement('div');
card.className = 'card stack wallet-transfer-card';
card.innerHTML = `
<h2 class="wallet-transfer-heading"></h2>
<div class="wallet-transfer-balances">
<div class="wallet-transfer-balance"><span>SOL</span><strong data-balance-sol>—</strong></div>
<div class="wallet-transfer-balance"><span data-usdt-name>USDT</span><strong data-balance-usdt>—</strong></div>
</div>
<label class="wallet-transfer-field"><span data-currency-label></span><select class="input wallet-transfer-select" data-currency><option value="SOL">SOL</option><option value="USDT">USDT</option></select></label>
<label class="wallet-transfer-field"><span data-amount-label></span><input class="input" data-amount type="text" inputmode="decimal" autocomplete="off" placeholder="0.01" /></label>
<div class="wallet-transfer-selected" data-selected hidden></div>
<label class="wallet-transfer-field"><span data-recipient-label></span><input class="input" data-recipient type="text" spellcheck="false" autocomplete="off" placeholder="Solana address (Base58)" /></label>
<label class="wallet-transfer-notice" data-notify-row hidden><input type="checkbox" data-notify /><span data-notify-label></span></label>
<p class="meta-muted wallet-transfer-hint" data-hint></p>
<button type="button" class="primary-btn wallet-transfer-submit" data-send></button>
<p class="meta-muted wallet-transfer-status" data-status role="status" aria-live="polite"></p>
`;
const q = (selector) => card.querySelector(`[data-${selector}]`);
q('currency-label').textContent = t('wallet_multi.asset');
q('amount-label').textContent = t('wallet_multi.amount');
q('recipient-label').textContent = t('wallet_multi.recipient');
q('notify-label').textContent = t('wallet_multi.notify');
q('notify-row').hidden = !recipientFromRoute;
q('send').textContent = t('wallet_multi.send');
q('hint').textContent = t('wallet_multi.no_stars');
q('selected').textContent = '';
card.querySelector('.wallet-transfer-heading').textContent = t('wallet_multi.transfer_title');
screen.append(card);
let disposed = false;
let busy = false;
// A chat-bound transfer has exactly one recipient; the wallet flow accepts only an address.
const recipientLogin = recipientFromRoute;
let selectedAddress = '';
let resolvingRecipient = Boolean(recipientLogin);
let address = '';
let usdt = { available: false, atomic: 0n, asset: getUsdtAsset() };
const endpoint = state.entrySettings.solanaServer;
const setStatus = (value) => { if (!disposed) q('status').textContent = value; };
const setBusy = (value) => {
busy = value;
q('currency').disabled = value;
q('amount').disabled = value;
q('recipient').disabled = value;
q('notify').disabled = value;
q('send').disabled = value || resolvingRecipient || (Boolean(recipientLogin) && !selectedAddress) || q('send').dataset.completed === 'true';
};
if (recipientLogin) {
q('selected').hidden = false;
q('selected').textContent = `${t('wallet_multi.contact')}: ${recipientLogin}`;
q('recipient').readOnly = true;
q('recipient').value = t('wallet_multi.resolving');
q('send').disabled = true;
void resolveContactBlockchainAddress(recipientLogin, endpoint)
.then((resolved) => {
if (disposed) return;
selectedAddress = resolved;
q('recipient').value = resolved;
setStatus('');
})
.catch((error) => {
if (disposed) return;
q('recipient').value = '';
setStatus(error.message || String(error));
})
.finally(() => {
if (disposed) return;
resolvingRecipient = false;
q('send').disabled = busy || !selectedAddress;
});
}
const refreshBalances = async () => {
try {
const wallet = await getWalletFromStoredBlockchainKey({
login: state.session.login, storagePwd: state.session.storagePwdInMemory,
});
if (disposed) return;
address = wallet.address;
const [sol, usdtResult] = await Promise.allSettled([
getBalanceSol({ endpoint, address }), getUsdtBalance({ endpoint, address }),
]);
if (disposed) return;
if (sol.status === 'fulfilled') q('balance-sol').textContent = `${sol.value.sol.toFixed(6)} SOL`;
if (usdtResult.status === 'fulfilled') {
usdt = usdtResult.value;
q('balance-usdt').textContent = usdt.available ? `${usdt.text} ${usdt.asset.label}` : t('wallet_multi.test_mint_missing');
} else q('balance-usdt').textContent = t('wallet_multi.balance_unavailable');
q('usdt-name').textContent = usdt.asset.label;
if (!usdt.available) q('currency').querySelector('option[value="USDT"]').disabled = true;
q('hint').textContent = usdt.asset.test ? `${t('wallet_multi.no_stars')} ${t('wallet_multi.devnet_disclaimer')}` : t('wallet_multi.no_stars');
} catch (error) { setStatus(error.message || String(error)); }
};
void refreshBalances();
q('send').addEventListener('click', async () => {
if (busy || disposed) return;
const currency = q('currency').value;
const amountText = q('amount').value;
const messageWanted = q('notify').checked;
let toAddress = String(q('recipient').value || '').trim();
let atomic;
try {
atomic = toAtomicAmount(amountText, currency === 'SOL' ? 9 : 6);
if (!state.session.login || !state.session.storagePwdInMemory) throw new Error('Не найдена авторизованная сессия SHiNE');
if (currency === 'SOL' && atomic > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('Сумма SOL слишком большая');
if (recipientLogin) {
if (!selectedAddress || resolvingRecipient) throw new Error('Адрес получателя ещё не получен');
// Refresh the binding at signing time, protect against stale/rotated blockchain keys.
toAddress = await resolveContactBlockchainAddress(recipientLogin, endpoint);
if (selectedAddress && toAddress !== selectedAddress) {
q('recipient').value = toAddress;
selectedAddress = toAddress;
throw new Error('Блокчейн-ключ получателя изменился. Проверьте новый адрес и повторите отправку.');
}
}
const solana = await loadSolanaWeb3();
const target = new solana.PublicKey(toAddress).toBase58();
if (address && target === address) throw new Error('Нельзя переводить самому себе');
// A wallet-to-wallet payment must never be sent to a mint, token account or executable program.
if (!solana.PublicKey.isOnCurve(new solana.PublicKey(target).toBytes())) {
throw new Error('Получатель должен быть обычным кошельком Solana (не PDA программы)');
}
const recipientInfo = await new solana.Connection(endpoint, 'confirmed').getAccountInfo(new solana.PublicKey(target), 'confirmed');
if (recipientInfo && (recipientInfo.executable || !recipientInfo.owner.equals(solana.SystemProgram.programId))) {
throw new Error('Адрес получателя не является обычным кошельком Solana');
}
if (currency === 'USDT' && !usdt.available) throw new Error('USDT в этой сети не настроен');
const display = `${formatAtomicAmount(atomic, currency === 'SOL' ? 9 : 6)} ${currency === 'SOL' ? 'SOL' : usdt.asset.label}`;
const contactLabel = recipientLogin ? `${recipientLogin}\n${target}` : target;
if (!window.confirm(`${t('wallet_multi.confirm')}\n${display}\n${contactLabel}`)) return;
setBusy(true);
setStatus(t('wallet_multi.sending'));
const wallet = await getWalletFromStoredBlockchainKey({ login: state.session.login, storagePwd: state.session.storagePwdInMemory });
if (wallet.address === target) throw new Error('Нельзя переводить самому себе');
const result = currency === 'SOL'
? await transferSolLamports({ endpoint, fromKeypair: wallet.keypair, toAddress: target, amountLamports: atomic })
: await transferUsdt({ endpoint, fromKeypair: wallet.keypair, toAddress: target, amountAtomic: atomic });
// The transfer is confirmed even if the user navigated away. Send requested DM anyway.
if (!disposed) {
setStatus(`${t('wallet_multi.success')}\n${result.signature}`);
q('send').textContent = t('wallet_multi.sent');
q('send').dataset.completed = 'true';
}
if (messageWanted && recipientLogin) {
try {
await authService.sendDirectMessage({
login: state.session.login, toLogin: recipientLogin,
storagePwd: state.session.storagePwdInMemory,
text: `${t('wallet_multi.dm_prefix')} ${display}\n${t('wallet_multi.dm_signature')}: ${result.signature}`,
});
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_sent')}`);
} catch (error) {
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_failed')}: ${error.message || error}`);
}
}
// Prevent accidental re-send on the success screen; user must navigate away to make another transfer.
if (!disposed) {
q('send').disabled = true;
q('send').dataset.completed = 'true';
void refreshBalances();
}
} catch (error) {
const message = error?.message || String(error);
if (/timed out|timeout|expired|confirmation/i.test(message)) {
// RPC timeout is not evidence that funds were not moved. Avoid duplicate send.
setStatus(`${t('wallet_multi.uncertain')}\n${message}`);
q('send').dataset.completed = 'true';
} else setStatus(message);
} finally {
if (!disposed) {
setBusy(false);
if (q('send').dataset.completed === 'true') q('send').disabled = true;
}
}
});
screen.cleanup = () => { disposed = true; };
return screen;
}
+36 -31
View File
@@ -8,7 +8,6 @@ import {
formatSol,
getBalanceSol,
getWalletFromStoredBlockchainKey,
transferSol,
} from '../services/solana-wallet-service.js';
import {
formatAr,
@@ -18,6 +17,7 @@ import {
} from '../services/arweave-wallet-service.js';
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
import { getUsdtBalance, getUsdtAsset } from '../services/solana-usdt-service.js';
import { openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
import { buildArweaveDataUrl, sha256HexFromArrayBuffer } from '../services/arweave-file-service.js';
import {
@@ -1848,7 +1848,12 @@ export function render({navigate, chrome}) {
const endpointLabel = document.createElement('p');
endpointLabel.className = 'meta-muted';
endpointLabel.textContent = `RPC: ${state.entrySettings.solanaServer}`;
balanceWrap.append(balanceLabel, balanceValue, updatedLabel, endpointLabel);
const usdtLine = document.createElement('div');
usdtLine.className = 'wallet-multi-usdt-line';
const usdtAsset = getUsdtAsset();
usdtLine.innerHTML = `<span></span><strong>—</strong>`;
usdtLine.querySelector('span').textContent = usdtAsset.label;
balanceWrap.append(balanceLabel, balanceValue, usdtLine, updatedLabel, endpointLabel);
const addressCard = document.createElement('div');
addressCard.className = 'card';
@@ -1858,6 +1863,10 @@ export function render({navigate, chrome}) {
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">—</p>
`;
const addressEl = addressCard.querySelector('#wallet-address-value');
const receiveHint = document.createElement('p');
receiveHint.className = 'meta-muted';
receiveHint.textContent = t('wallet_multi.receive_hint');
addressCard.append(receiveHint);
enableAddressCopy(addressEl, () => walletAddress);
card.append(balanceWrap, addressCard);
@@ -1867,7 +1876,7 @@ export function render({navigate, chrome}) {
actions.innerHTML = `
<div class="row">
<button class="primary-btn" id="refresh-balance" style="flex:1;">${th('screens.wallet_view.text_293')}</button>
<button class="primary-btn" id="send-sol" style="flex:1;">${th('screens.wallet_view.text_294')}</button>
<button class="primary-btn" id="send-sol" style="flex:1;">${t('wallet_multi.transfer_title')}</button>
</div>
`;
@@ -1887,9 +1896,18 @@ export function render({navigate, chrome}) {
});
if (modeToken !== activeModeToken) return;
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
let tokenErrorText = '';
try {
const token = await getUsdtBalance({ endpoint: state.entrySettings.solanaServer, address: walletAddress });
if (modeToken !== activeModeToken) return;
usdtLine.querySelector('strong').textContent = token.available ? token.text : t('wallet_multi.test_mint_missing');
} catch (tokenError) {
usdtLine.querySelector('strong').textContent = t('wallet_multi.balance_unavailable');
tokenErrorText = `${t('wallet_multi.balance_unavailable')}: ${tokenError.message || tokenError}`;
}
updatedLabel.textContent = t('screens.wallet_view.text_181', { value1: nowRu() });
endpointLabel.textContent = `RPC: ${balance.endpoint}`;
setStatus(t('screens.wallet_view.text_085'));
setStatus(tokenErrorText || t('screens.wallet_view.text_085'));
} catch (error) {
if (modeToken !== activeModeToken) return;
setStatus(actionErrorText(t('screens.wallet_view.text_086'), error));
@@ -1902,34 +1920,17 @@ export function render({navigate, chrome}) {
void refreshBalance();
});
sendBtn.addEventListener('click', async () => {
if (!walletCtx?.keypair) {
setStatus(t('screens.wallet_view.text_087'));
return;
}
const toAddress = window.prompt(t('dialogs.pages.wallet_view.prompt_002'), '');
if (!toAddress) return;
const amountRaw = window.prompt(t('dialogs.pages.wallet_view.prompt_003'), '0.01');
if (!amountRaw) return;
sendBtn.addEventListener('click', () => navigate('wallet/transfer'));
sendBtn.disabled = true;
try {
const tx = await transferSol({
endpoint: state.entrySettings.solanaServer,
fromKeypair: walletCtx.keypair,
toAddress,
amountSol: Number(String(amountRaw || '').replace(',', '.')),
});
if (modeToken !== activeModeToken) return;
setStatus(t('screens.wallet_view.text_182', { value1: tx.signature }));
await refreshBalance();
} catch (error) {
if (modeToken !== activeModeToken) return;
setStatus(actionErrorText(t('screens.wallet_view.text_088'), error));
} finally {
sendBtn.disabled = false;
}
});
const swapHint = document.createElement('p');
swapHint.className = 'meta-muted wallet-jupiter-hint';
swapHint.textContent = t('wallet_swap.wallet_hint');
const swapButton = document.createElement('button');
swapButton.type = 'button';
swapButton.className = 'secondary-btn wallet-jupiter-link';
swapButton.textContent = t('wallet_swap.wallet_button');
swapButton.addEventListener('click', () => navigate('wallet/swap'));
actions.append(swapButton, swapHint);
content.append(backBtn, card, actions);
setStatus(t('screens.wallet_view.text_089'));
@@ -1986,6 +1987,10 @@ export function render({navigate, chrome}) {
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">–</p>
`;
const addressEl = addressCard.querySelector('#wallet-address-value');
const receiveHint = document.createElement('p');
receiveHint.className = 'meta-muted';
receiveHint.textContent = t('wallet_multi.receive_hint');
addressCard.append(receiveHint);
enableAddressCopy(addressEl, () => walletAddress);
const helpCard = document.createElement('details');