SHA256
Сделаны переводы другим пользователям
This commit is contained in:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user