import { t } from '../i18n/index.js';
import { formatDateTime } from '../i18n/format.js';
import { escapeHtml } from '../services/attachment-format.js';
import { arweaveBlockUrl, checkArweavePayload, checkSolanaAuthor, readSignedBlock, signedDataItemFilename } from '../services/blockchain-proof-service.js';
import { showToast } from '../services/channels-ux.js';
const validHash = (value) => /^[0-9a-f]{64}$/iu.test(String(value || ''));
const label = (key) => t(`blockchain_details.${key}`);
const safe = (value) => escapeHtml(String(value ?? ''));
const shortened = (value) => String(value || '').length > 24
? `${String(value).slice(0, 12)}…${String(value).slice(-8)}` : String(value || '');
function asVersions(details) {
const raw = Array.isArray(details?.raw?.versions) ? details.raw.versions : [];
if (raw.length) return raw.map((v, i) => ({ ...v, versionIndex: Number(v.versionIndex || i + 1) }));
return [{ versionIndex: 1, blockNumber: details.blockNumber, blockHash: details.blockHash,
createdAtMs: details.createdAtMs, arweaveDataItemId: details.raw?.arweaveDataItemId || '',
arweavePublishPending: details.raw?.arweavePublishPending,
arweavePublishedAtMs: details.raw?.arweavePublishedAtMs,
signedDataItemBytes: details.raw?.signedDataItemBytes }];
}
function field(title, value, { code = false } = {}) {
const valueHtml = code ? `${safe(value)}` : `${safe(value)}`;
return `
${safe(title)}${valueHtml}
`;
}
function statusFor(version) {
if (version?.arweavePublishedAtMs > 0) return { color: 'success', text: label('published') };
if (version?.arweavePublishPending === true) return { color: 'pending', text: label('pending') };
return { color: 'unknown', text: label('unknown') };
}
async function copy(value) {
const text = String(value || '');
if (!text) return;
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
} else {
const input = document.createElement('textarea');
input.value = text; input.style.position = 'fixed'; input.style.opacity = '0';
document.body.append(input); input.select(); document.execCommand('copy'); input.remove();
}
showToast(label('copied'));
}
function resultRow(name, status, reason = '') {
const mark = status === 'valid' ? '✓' : status === 'invalid' ? '✕' : '—';
const description = status === 'valid' ? label('verified') : status === 'invalid' ? label('failed') : label('not_verified');
return `${mark}${safe(name)}: ${safe(description)}${reason ? `${safe(reason)}` : ''}
`;
}
/** Единый диалог для ленты канала и страницы обсуждения. */
export function openBlockchainDetailsModal(details, { authService, solanaEndpoint, isActive = () => true } = {}) {
const root = document.getElementById('modal-root');
if (!root) return;
const versions = asVersions(details);
let current = versions.length - 1;
let busy = false;
const rawText = JSON.stringify(details.raw || {}, null, 2);
root.innerHTML = `
${versions.length > 1 ? `
` : ''}
${safe(label('technical'))}
${safe(rawText)}
`;
const get = (id) => root.querySelector(`#${id}`);
const currentVersion = () => versions[current];
const content = get('block-proof-content');
const results = get('block-proof-results');
const button = get('block-proof-download');
const verify = get('block-proof-verify');
const close = () => { if (get('blockchain-details-modal')) root.innerHTML = ''; };
function renderVersion() {
const v = currentVersion();
const archive = statusFor(v);
const hash = validHash(v.blockHash) ? v.blockHash : '';
const url = arweaveBlockUrl(v.arweaveDataItemId);
const date = Number(v.createdAtMs || details.createdAtMs);
content.innerHTML = `
${field(label('author'), details.authorLogin || '—')}
${field(label('blockchain'), details.authorBlockchainName || '—', { code: true })}
${field(label('block_number'), v.blockNumber)}
${field(label('created'), date > 0 ? formatDateTime(new Date(date)) : '—')}
${field(label('storage'), 'Arweave')}
${field(label('signed_size'), Number.isInteger(v.signedDataItemBytes) ? `${v.signedDataItemBytes} ${label('bytes')}` : '—')}
${v.attachmentMetadataValid === false ? `${safe(label('invalid_attachment'))}
` : ''}
${safe(archive.text)}
${safe(label('hash'))}${safe(shortened(hash) || '—')}
${url ? `Arweave DataItem ID${safe(shortened(v.arweaveDataItemId))}
` : ''}`;
get('block-proof-open').href = url || '#';
get('block-proof-open').hidden = !url;
get('block-proof-copy-url').disabled = !url;
get('block-proof-copy-hash')?.addEventListener('click', () => { void copy(hash); });
get('block-proof-copy-id')?.addEventListener('click', () => { void copy(v.arweaveDataItemId); });
results.hidden = true;
results.replaceChildren();
}
async function signedBlock() {
const v = currentVersion();
if (!validHash(v.blockHash)) throw new Error(label('missing_hash'));
return readSignedBlock({ authService, blockchainName: details.authorBlockchainName,
blockNumber: v.blockNumber, blockHash: v.blockHash, dataItemId: v.arweaveDataItemId });
}
get('block-proof-version')?.addEventListener('change', (event) => {
if (busy) { event.target.value = String(current); return; }
current = Number(event.target.value); renderVersion();
});
get('block-proof-copy-url')?.addEventListener('click', () => { void copy(arweaveBlockUrl(currentVersion().arweaveDataItemId)); });
get('block-proof-copy-raw')?.addEventListener('click', () => { void copy(rawText); });
get('block-proof-close')?.addEventListener('click', close);
button.addEventListener('click', async () => {
if (busy) return;
busy = true; button.disabled = true; verify.disabled = true;
try {
const proof = await signedBlock();
if (!isActive() || !get('blockchain-details-modal')) return;
const blobUrl = URL.createObjectURL(new Blob([proof.bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a');
link.href = blobUrl;
link.download = signedDataItemFilename(details.authorBlockchainName, currentVersion().blockNumber);
document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
} catch (error) { if (isActive()) showToast(String(error?.message || error), { kind: 'error' }); }
finally { busy = false; button.disabled = false; verify.disabled = false; }
});
verify.addEventListener('click', async () => {
if (busy) return;
busy = true; verify.disabled = true; button.disabled = true;
const select = get('block-proof-version'); if (select) select.disabled = true;
results.hidden = false; results.textContent = label('checking');
try {
const proof = await signedBlock();
const id = currentVersion().arweaveDataItemId || proof.actualId;
const [arweave, solana] = await Promise.all([
checkArweavePayload(id, proof.data),
checkSolanaAuthor({ authorLogin: details.authorLogin, blockchainName: details.authorBlockchainName,
owner32: proof.owner32, solanaEndpoint }),
]);
if (!isActive() || !get('blockchain-details-modal')) return;
results.innerHTML = [
resultRow(label('signature'), 'valid'),
resultRow(label('integrity'), 'valid'),
resultRow(label('arweave_check'), arweave.status, arweave.reason),
resultRow(label('solana_check'), solana.status, solana.reason),
`${safe(label('proof_note'))}
`,
].join('');
} catch (error) {
if (!isActive() || !get('blockchain-details-modal')) return;
results.innerHTML = resultRow(label('signed_check'), 'unavailable', String(error?.message || error));
} finally {
busy = false;
if (get('blockchain-details-modal')) { verify.disabled = false; button.disabled = false; if (select) select.disabled = false; }
}
});
renderVersion();
}