SHA256
feat(ui): кошелек на device.key и проверки серверов (тоже пока не проверено)
This commit is contained in:
@@ -1,42 +1,67 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import { wallet } from '../mock-data.js';
|
||||
import { state } from '../state.js';
|
||||
import {
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getTopupSiteUrl,
|
||||
getWalletFromStoredDeviceKey,
|
||||
requestAirdropSol,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-view', title: 'Кошелёк' };
|
||||
|
||||
function nowRu() {
|
||||
return new Date().toLocaleString('ru-RU');
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
let statusText = 'Данные демонстрационные';
|
||||
|
||||
let walletCtx = null;
|
||||
let walletAddress = '';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = 'Инициализация wallet.key...';
|
||||
|
||||
const updateStatus = (text) => {
|
||||
statusText = text;
|
||||
status.textContent = statusText;
|
||||
};
|
||||
|
||||
const screenTitle = 'Кошелёк';
|
||||
screen.append(
|
||||
renderHeader({
|
||||
title: 'Кошелёк',
|
||||
title: screenTitle,
|
||||
leftAction: { label: '←', onClick: () => navigate('profile-view') },
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
card.innerHTML = `
|
||||
<div>
|
||||
<p class="meta-muted">Баланс</p>
|
||||
<h2 style="font-size:30px;">${wallet.balanceSOL} SOL</h2>
|
||||
<p class="meta-muted">Обновлено: ${wallet.updatedAt}</p>
|
||||
</div>
|
||||
<div class="card" style="padding:10px;">
|
||||
<p class="meta-muted" style="margin-bottom:6px;">Публичный адрес</p>
|
||||
<p style="font-size:13px; line-height:1.4; word-break:break-all;">${wallet.publicAddress}</p>
|
||||
</div>
|
||||
|
||||
const balanceWrap = document.createElement('div');
|
||||
const balanceLabel = document.createElement('p');
|
||||
balanceLabel.className = 'meta-muted';
|
||||
balanceLabel.textContent = 'Баланс (Solana)';
|
||||
const balanceValue = document.createElement('h2');
|
||||
balanceValue.style.fontSize = '30px';
|
||||
balanceValue.textContent = '— SOL';
|
||||
const updatedLabel = document.createElement('p');
|
||||
updatedLabel.className = 'meta-muted';
|
||||
updatedLabel.textContent = 'Обновлено: —';
|
||||
const endpointLabel = document.createElement('p');
|
||||
endpointLabel.className = 'meta-muted';
|
||||
endpointLabel.textContent = `RPC: ${state.entrySettings.solanaServer}`;
|
||||
balanceWrap.append(balanceLabel, balanceValue, updatedLabel, endpointLabel);
|
||||
|
||||
const addressCard = document.createElement('div');
|
||||
addressCard.className = 'card';
|
||||
addressCard.style.padding = '10px';
|
||||
addressCard.innerHTML = `
|
||||
<p class="meta-muted" style="margin-bottom:6px;">Публичный адрес (wallet.key = device.key)</p>
|
||||
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">—</p>
|
||||
`;
|
||||
|
||||
card.append(balanceWrap, addressCard);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'stack';
|
||||
actions.innerHTML = `
|
||||
@@ -50,29 +75,126 @@ export function render({ navigate }) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
actions.querySelector('#copy-address').addEventListener('click', async () => {
|
||||
const copyBtn = actions.querySelector('#copy-address');
|
||||
const refreshBtn = actions.querySelector('#refresh-balance');
|
||||
const sendBtn = actions.querySelector('#send-sol');
|
||||
const topupBtn = actions.querySelector('#topup-sol');
|
||||
const addressEl = addressCard.querySelector('#wallet-address-value');
|
||||
|
||||
const setStatus = (text) => {
|
||||
status.textContent = String(text || '');
|
||||
};
|
||||
|
||||
const refreshBalance = async () => {
|
||||
if (!walletAddress) {
|
||||
setStatus('Кошелёк не инициализирован.');
|
||||
return;
|
||||
}
|
||||
refreshBtn.disabled = true;
|
||||
try {
|
||||
await navigator.clipboard.writeText(wallet.publicAddress);
|
||||
updateStatus('Адрес скопирован в буфер обмена');
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address: walletAddress,
|
||||
});
|
||||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||||
updatedLabel.textContent = `Обновлено: ${nowRu()}`;
|
||||
endpointLabel.textContent = `RPC: ${balance.endpoint}`;
|
||||
setStatus('Баланс обновлён.');
|
||||
} catch (error) {
|
||||
setStatus(`Не удалось получить баланс: ${error?.message || 'unknown'}`);
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
copyBtn.addEventListener('click', async () => {
|
||||
if (!walletAddress) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(walletAddress);
|
||||
setStatus('Адрес скопирован в буфер обмена');
|
||||
} catch {
|
||||
updateStatus('Не удалось скопировать в этом браузере');
|
||||
setStatus('Не удалось скопировать адрес в этом браузере');
|
||||
}
|
||||
});
|
||||
|
||||
actions.querySelector('#refresh-balance').addEventListener('click', () => {
|
||||
updateStatus(`Баланс обновлен: ${wallet.balanceSOL} SOL`);
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
void refreshBalance();
|
||||
});
|
||||
|
||||
actions.querySelector('#send-sol').addEventListener('click', () => {
|
||||
updateStatus('Демо-функция: перевод будет добавлен позже');
|
||||
sendBtn.addEventListener('click', async () => {
|
||||
if (!walletCtx?.keypair) {
|
||||
setStatus('Перевод недоступен: wallet.key не загружен.');
|
||||
return;
|
||||
}
|
||||
const toAddress = window.prompt('Введите адрес получателя (Solana):', '');
|
||||
if (!toAddress) return;
|
||||
const amountRaw = window.prompt('Введите сумму SOL для перевода:', '0.01');
|
||||
if (!amountRaw) return;
|
||||
|
||||
sendBtn.disabled = true;
|
||||
try {
|
||||
const tx = await transferSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
fromKeypair: walletCtx.keypair,
|
||||
toAddress,
|
||||
amountSol: Number(String(amountRaw || '').replace(',', '.')),
|
||||
});
|
||||
setStatus(`Перевод отправлен. Signature: ${tx.signature}`);
|
||||
await refreshBalance();
|
||||
} catch (error) {
|
||||
setStatus(`Ошибка перевода: ${error?.message || 'unknown'}`);
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
actions.querySelector('#topup-sol').addEventListener('click', () => {
|
||||
updateStatus('Демо-функция: пополнение будет добавлено позже');
|
||||
topupBtn.addEventListener('click', async () => {
|
||||
if (!walletAddress) {
|
||||
setStatus('Кошелёк не инициализирован.');
|
||||
return;
|
||||
}
|
||||
|
||||
const openSite = window.confirm(
|
||||
'Кнопка будет переводить на отдельный сайт пополнения.\n\nНажмите OK, чтобы открыть сайт.\nНажмите Отмена, чтобы выполнить тестовое пополнение (airdrop 1 SOL на DevNet).'
|
||||
);
|
||||
if (openSite) {
|
||||
window.open(getTopupSiteUrl(), '_blank', 'noopener,noreferrer');
|
||||
setStatus('Открыт сайт пополнения. Пока также доступно тестовое пополнение.');
|
||||
return;
|
||||
}
|
||||
|
||||
topupBtn.disabled = true;
|
||||
try {
|
||||
const drop = await requestAirdropSol({
|
||||
endpoint: state.entrySettings.solanaServer,
|
||||
address: walletAddress,
|
||||
amountSol: 1,
|
||||
});
|
||||
setStatus(`Тестовое пополнение выполнено (airdrop 1 SOL). Signature: ${drop.signature}`);
|
||||
await refreshBalance();
|
||||
} catch (error) {
|
||||
setStatus(`Ошибка тестового пополнения: ${error?.message || 'unknown'}`);
|
||||
} finally {
|
||||
topupBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
updateStatus(statusText);
|
||||
(async () => {
|
||||
try {
|
||||
walletCtx = await getWalletFromStoredDeviceKey({
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
walletAddress = walletCtx.address;
|
||||
addressEl.textContent = walletAddress;
|
||||
await refreshBalance();
|
||||
} catch (error) {
|
||||
addressEl.textContent = 'wallet.key недоступен';
|
||||
setStatus(`Не удалось инициализировать кошелёк: ${error?.message || 'unknown'}`);
|
||||
}
|
||||
})();
|
||||
|
||||
screen.append(card, actions, status);
|
||||
return screen;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user