ваше сообщение коммита

This commit is contained in:
2025-09-30 00:23:37 +03:00
parent ca718e3178
commit 4b03951b31
77 changed files with 17161 additions and 7255 deletions

View File

@@ -156,12 +156,8 @@ let unsubscribe = null;
onMounted(() => {
// console.log('[CrmView] Компонент загружен');
// Если пользователь авторизован, загружаем данные
if (auth.isAuthenticated.value) {
loadDLEs();
} else {
isLoading.value = false;
}
// Загружаем DLE для всех пользователей (авторизованных и неавторизованных)
loadDLEs();
// Подписка на события авторизации
unsubscribe = eventBus.on('auth-state-changed', handleAuthEvent);

View File

@@ -40,6 +40,7 @@
</div>
</div>
<div v-if="isLoadingDles" class="loading-dles">
<p>Загрузка деплоированных DLE...</p>
</div>
@@ -56,6 +57,7 @@
class="dle-card"
@click="openDleManagement(dle.dleAddress)"
>
<div class="dle-header">
<div class="dle-title-section">
<img
@@ -99,18 +101,18 @@
<strong>Адреса контрактов:</strong>
<div class="addresses-list">
<div
v-for="network in dle.deployedNetworks || [{ chainId: 11155111, address: dle.dleAddress }]"
:key="network.chainId"
v-for="chainId in (dle.supportedChainIds || [11155111])"
:key="chainId"
class="address-item"
>
<span class="chain-name">{{ getChainName(network.chainId) }}:</span>
<span class="chain-name">{{ getChainName(chainId) }}:</span>
<a
:href="getExplorerUrl(network.chainId, network.address)"
:href="getExplorerUrl(chainId, dle.dleAddress)"
target="_blank"
class="address-link"
@click.stop
>
{{ shortenAddress(network.address) }}
{{ shortenAddress(dle.dleAddress) }}
<i class="fas fa-external-link-alt"></i>
</a>
</div>
@@ -253,14 +255,22 @@ async function loadDeployedDles() {
const dlesWithBlockchainData = await Promise.all(
dlesFromApi.map(async (dle) => {
try {
console.log(`[ManagementView] Читаем данные из блокчейна для ${dle.dleAddress}`);
// Используем адрес из deployedNetworks если dleAddress null
const dleAddress = dle.dleAddress || (dle.deployedNetworks && dle.deployedNetworks.length > 0 ? dle.deployedNetworks[0].address : null);
if (!dleAddress) {
console.warn(`[ManagementView] Нет адреса для DLE ${dle.deployment_id || 'unknown'}`);
return dle;
}
console.log(`[ManagementView] Читаем данные из блокчейна для ${dleAddress}`);
// Читаем данные из блокчейна
const blockchainResponse = await api.post('/blockchain/read-dle-info', {
dleAddress: dle.dleAddress
dleAddress: dleAddress
});
console.log(`[ManagementView] Ответ от блокчейна для ${dle.dleAddress}:`, blockchainResponse.data);
console.log(`[ManagementView] Ответ от блокчейна для ${dleAddress}:`, blockchainResponse.data);
if (blockchainResponse.data.success) {
const blockchainData = blockchainResponse.data.data;
@@ -376,7 +386,15 @@ function formatTokenAmount(amount) {
const num = parseFloat(amount);
if (num === 0) return '0';
// Всегда показываем полное число с разделителями тысяч
// Для очень маленьких чисел показываем с большей точностью
if (num < 1) {
return num.toLocaleString('ru-RU', {
minimumFractionDigits: 0,
maximumFractionDigits: 18
});
}
// Для больших чисел показываем с разделителями тысяч
return num.toLocaleString('ru-RU', { maximumFractionDigits: 0 });
}
@@ -812,6 +830,7 @@ onMounted(() => {
}
/* Адаптивность */
@media (max-width: 768px) {
.dle-title-section {

View File

@@ -84,8 +84,11 @@
v-model.number="newToken.minBalance"
class="form-control"
placeholder="0"
min="0"
step="0.01"
:disabled="!canEdit"
>
<small class="form-text">Минимальный баланс токена для получения доступа</small>
</div>
<!-- Настройки прав доступа -->
@@ -158,6 +161,12 @@ async function addToken() {
return;
}
// Валидация порогов доступа
if (newToken.readonlyThreshold >= newToken.editorThreshold) {
alert('Минимум токенов для Read-Only доступа должен быть меньше минимума для Editor доступа');
return;
}
const tokenData = {
name: newToken.name,
address: newToken.address,

View File

@@ -66,34 +66,68 @@ const emailAuth = {
<style scoped>
.webssh-settings-block {
background: #fff;
border-radius: var(--radius-lg);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
margin-top: 20px;
margin-bottom: 20px;
width: 100%;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
padding: 2rem;
margin: 2rem auto;
max-width: 1000px;
position: relative;
overflow-x: auto;
}
.close-btn {
position: absolute;
top: 18px;
right: 18px;
top: 1.5rem;
right: 1.5rem;
background: none;
border: none;
font-size: 2rem;
font-size: 1.5rem;
cursor: pointer;
color: #bbb;
transition: color 0.2s;
color: #666;
padding: 0.5rem;
border-radius: 50%;
transition: all 0.2s;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.close-btn:hover {
background: #f0f0f0;
color: #333;
}
h2 {
margin-bottom: 0.5rem;
margin: 0 0 0.5rem 0;
color: var(--color-primary);
font-size: 2rem;
font-weight: 700;
padding-right: 3rem;
}
.desc {
color: #666;
margin-bottom: 1.5rem;
margin-bottom: 2rem;
font-size: 1.1rem;
line-height: 1.5;
}
/* Адаптивность */
@media (max-width: 768px) {
.webssh-settings-block {
margin: 1rem;
padding: 1.5rem;
}
h2 {
font-size: 1.5rem;
padding-right: 2.5rem;
}
.desc {
font-size: 1rem;
}
}
</style>

File diff suppressed because it is too large Load Diff

View File

@@ -30,91 +30,29 @@
<button class="close-btn" @click="goBackToBlocks">×</button>
</div>
<!-- Блоки операций DLE -->
<div class="operations-blocks">
<div class="blocks-header">
<h4>Типы операций DLE контракта</h4>
<p>Выберите тип операции для создания предложения</p>
<!-- Информация для неавторизованных пользователей -->
<div v-if="!props.isAuthenticated" class="auth-notice">
<div class="alert alert-info">
<i class="fas fa-info-circle"></i>
<strong>Для создания предложений необходимо авторизоваться в приложении</strong>
<p class="mb-0 mt-2">Подключите кошелек в сайдбаре для создания новых предложений</p>
</div>
<!-- Информация для неавторизованных пользователей -->
<div v-if="!props.isAuthenticated" class="auth-notice">
<div class="alert alert-info">
<i class="fas fa-info-circle"></i>
<strong>Для создания предложений необходимо авторизоваться в приложении</strong>
<p class="mb-0 mt-2">Подключите кошелек в сайдбаре для создания новых предложений</p>
</div>
</div>
<!-- Блоки операций -->
<div class="operations-grid">
<!-- Управление токенами -->
</div>
<!-- Блоки операций -->
<div class="operations-grid">
<!-- Основные операции DLE -->
<div class="operation-category">
<h5>💸 Управление токенами</h5>
<h5>Основные операции DLE</h5>
<div class="operation-blocks">
<div class="operation-block">
<div class="operation-icon">💸</div>
<h6>Передача токенов</h6>
<p>Перевод токенов DLE другому адресу через governance</p>
<button class="create-btn" @click="openTransferForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
</div>
</div>
<!-- Управление модулями -->
<div class="operation-category">
<h5>🔧 Управление модулями</h5>
<div class="operation-blocks">
<div class="operation-block">
<div class="operation-icon"></div>
<h6>Добавить модуль</h6>
<p>Добавление нового модуля в DLE контракт</p>
<button class="create-btn" @click="openAddModuleForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<div class="operation-icon"></div>
<h6>Удалить модуль</h6>
<p>Удаление существующего модуля из DLE контракта</p>
<button class="create-btn" @click="openRemoveModuleForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
</div>
</div>
<!-- Управление сетями -->
<div class="operation-category">
<h5>🌐 Управление сетями</h5>
<div class="operation-blocks">
<div class="operation-block">
<div class="operation-icon"></div>
<h6>Добавить сеть</h6>
<p>Добавление новой поддерживаемой блокчейн сети</p>
<button class="create-btn" @click="openAddChainForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<div class="operation-icon"></div>
<h6>Удалить сеть</h6>
<p>Удаление поддерживаемой блокчейн сети</p>
<button class="create-btn" @click="openRemoveChainForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
</div>
</div>
<!-- Управление настройками DLE -->
<div class="operation-category">
<h5> Настройки DLE</h5>
<div class="operation-blocks">
<div class="operation-block">
<div class="operation-icon">📝</div>
<h6>Обновить данные DLE</h6>
<p>Изменение основной информации о DLE (название, символ, адрес и т.д.)</p>
<button class="create-btn" @click="openUpdateDLEInfoForm" :disabled="!props.isAuthenticated">
@@ -122,7 +60,6 @@
</button>
</div>
<div class="operation-block">
<div class="operation-icon">📊</div>
<h6>Изменить кворум</h6>
<p>Изменение процента голосов, необходимого для принятия решений</p>
<button class="create-btn" @click="openUpdateQuorumForm" :disabled="!props.isAuthenticated">
@@ -130,7 +67,6 @@
</button>
</div>
<div class="operation-block">
<div class="operation-icon"></div>
<h6>Изменить время голосования</h6>
<p>Настройка минимального и максимального времени голосования</p>
<button class="create-btn" @click="openUpdateVotingDurationsForm" :disabled="!props.isAuthenticated">
@@ -138,7 +74,41 @@
</button>
</div>
<div class="operation-block">
<div class="operation-icon">🖼</div>
<h6>Оффчейн действие</h6>
<p>Создание предложения для выполнения оффчейн операций в приложении</p>
<button class="create-btn" @click="openOffchainActionForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<h6>Добавить модуль</h6>
<p>Добавление нового модуля в DLE контракт</p>
<button class="create-btn" @click="openAddModuleForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<h6>Удалить модуль</h6>
<p>Удаление существующего модуля из DLE контракта</p>
<button class="create-btn" @click="openRemoveModuleForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<h6>Добавить сеть</h6>
<p>Добавление новой поддерживаемой блокчейн сети</p>
<button class="create-btn" @click="openAddChainForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<h6>Удалить сеть</h6>
<p>Удаление поддерживаемой блокчейн сети</p>
<button class="create-btn" @click="openRemoveChainForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
<div class="operation-block">
<h6>Изменить логотип</h6>
<p>Обновление URI логотипа DLE для отображения в блокчейн-сканерах</p>
<button class="create-btn" @click="openSetLogoURIForm" :disabled="!props.isAuthenticated">
@@ -166,10 +136,8 @@
:key="operation.id"
class="operation-block module-operation-block"
>
<div class="operation-icon">{{ operation.icon }}</div>
<h6>{{ operation.name }}</h6>
<p>{{ operation.description }}</p>
<div class="operation-category-tag">{{ operation.category }}</div>
<button
class="create-btn"
@click="openModuleOperationForm(moduleOperation.moduleType, operation)"
@@ -182,21 +150,6 @@
</div>
</div>
<!-- Оффчейн операции -->
<div class="operation-category">
<h5>📋 Оффчейн операции</h5>
<div class="operation-blocks">
<div class="operation-block">
<div class="operation-icon">📄</div>
<h6>Оффчейн действие</h6>
<p>Создание предложения для выполнения оффчейн операций в приложении</p>
<button class="create-btn" @click="openOffchainActionForm" :disabled="!props.isAuthenticated">
Создать
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</BaseLayout>
@@ -259,7 +212,6 @@ const availableChains = ref([]);
// Состояние модулей и их операций
const moduleOperations = ref([]);
const isLoadingModuleOperations = ref(false);
const modulesWebSocket = ref(null);
const isModulesWSConnected = ref(false);
// Функции для открытия отдельных форм операций
@@ -269,8 +221,11 @@ function openTransferForm() {
}
function openAddModuleForm() {
// TODO: Открыть форму для добавления модуля
alert('Форма добавления модуля будет реализована');
if (dleAddress.value) {
router.push(`/management/add-module?address=${dleAddress.value}`);
} else {
router.push('/management/add-module');
}
}
function openRemoveModuleForm() {
@@ -325,13 +280,7 @@ function openModuleOperationForm(moduleType, operation) {
// Получить иконку для типа модуля
function getModuleIcon(moduleType) {
const icons = {
treasury: '💰',
timelock: '⏰',
reader: '📖',
hierarchicalVoting: '🗳️'
};
return icons[moduleType] || '🔧';
return '';
}
// Функции
@@ -364,6 +313,9 @@ async function loadDleData() {
// Загружаем операции модулей
await loadModuleOperations();
// Повторно подписываемся на обновления модулей для нового DLE
resubscribeToModules();
} catch (error) {
console.error('Ошибка загрузки данных DLE из блокчейна:', error);
} finally {
@@ -401,49 +353,61 @@ async function loadModuleOperations() {
// WebSocket функции для модулей
function connectModulesWebSocket() {
if (modulesWebSocket.value && modulesWebSocket.value.readyState === WebSocket.OPEN) {
if (isModulesWSConnected.value) {
return;
}
const wsUrl = `ws://localhost:8000/ws/deployment`;
modulesWebSocket.value = new WebSocket(wsUrl);
modulesWebSocket.value.onopen = () => {
console.log('[CreateProposalView] WebSocket модулей соединение установлено');
isModulesWSConnected.value = true;
try {
// Подключаемся через существующий WebSocket клиент
wsClient.connect();
// Подписываемся на обновления модулей для текущего DLE
if (dleAddress.value) {
modulesWebSocket.value.send(JSON.stringify({
type: 'subscribe',
dleAddress: dleAddress.value
}));
}
};
modulesWebSocket.value.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
// Подписываемся на события deployment_update
wsClient.on('deployment_update', (data) => {
console.log('[CreateProposalView] Получено обновление деплоя:', data);
handleModulesWebSocketMessage(data);
} catch (error) {
console.error('[CreateProposalView] Ошибка парсинга WebSocket сообщения модулей:', error);
}
};
});
modulesWebSocket.value.onclose = () => {
console.log('[CreateProposalView] WebSocket модулей соединение закрыто');
// Подписываемся на подтверждение подписки
wsClient.on('subscribed', (data) => {
console.log('[CreateProposalView] Подписка подтверждена:', data);
});
// Подписываемся на обновления модулей
wsClient.on('modules_updated', (data) => {
console.log('[CreateProposalView] Модули обновлены:', data);
// Перезагружаем операции модулей при обновлении
loadModuleOperations();
});
// Подписываемся на статус деплоя
wsClient.on('deployment_status', (data) => {
console.log('[CreateProposalView] Статус деплоя:', data);
handleModulesWebSocketMessage(data);
});
// Подписываемся на событие подключения
wsClient.on('connected', () => {
console.log('[CreateProposalView] WebSocket подключен, подписываемся на модули');
if (dleAddress.value) {
wsClient.ws.send(JSON.stringify({
type: 'subscribe',
dleAddress: dleAddress.value
}));
console.log('[CreateProposalView] Подписка на модули отправлена для DLE:', dleAddress.value);
}
});
isModulesWSConnected.value = true;
console.log('[CreateProposalView] WebSocket модулей соединение установлено');
} catch (error) {
console.error('[CreateProposalView] Ошибка подключения WebSocket модулей:', error);
isModulesWSConnected.value = false;
// Переподключаемся через 5 секунд
setTimeout(() => {
connectModulesWebSocket();
}, 5000);
};
modulesWebSocket.value.onerror = (error) => {
console.error('[CreateProposalView] Ошибка WebSocket модулей:', error);
isModulesWSConnected.value = false;
};
}
}
function handleModulesWebSocketMessage(data) {
@@ -471,10 +435,30 @@ function handleModulesWebSocketMessage(data) {
}
function disconnectModulesWebSocket() {
if (modulesWebSocket.value) {
modulesWebSocket.value.close();
modulesWebSocket.value = null;
if (isModulesWSConnected.value) {
// Отписываемся от всех событий
wsClient.off('deployment_update');
wsClient.off('subscribed');
wsClient.off('modules_updated');
wsClient.off('deployment_status');
wsClient.off('connected');
isModulesWSConnected.value = false;
console.log('[CreateProposalView] WebSocket модулей отключен');
}
}
// Функция для повторной подписки при изменении DLE адреса
function resubscribeToModules() {
if (isModulesWSConnected.value && wsClient.ws && wsClient.ws.readyState === WebSocket.OPEN && dleAddress.value) {
wsClient.ws.send(JSON.stringify({
type: 'subscribe',
dleAddress: dleAddress.value
}));
console.log('[CreateProposalView] Повторная подписка на модули для DLE:', dleAddress.value);
} else if (wsClient.ws && wsClient.ws.readyState === WebSocket.CONNECTING) {
// Если соединение еще устанавливается, ждем события подключения
console.log('[CreateProposalView] WebSocket еще подключается, ждем события connected');
}
}
@@ -558,32 +542,6 @@ onUnmounted(() => {
color: #333;
}
/* Стили для блоков операций */
.operations-blocks {
background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
border-radius: 12px;
padding: 2rem;
border: 1px solid #e9ecef;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.blocks-header {
margin-bottom: 2rem;
text-align: center;
}
.blocks-header h4 {
color: var(--color-primary);
margin: 0 0 0.5rem 0;
font-size: 1.5rem;
font-weight: 600;
}
.blocks-header p {
color: #6c757d;
margin: 0;
font-size: 1rem;
}
.auth-notice {
margin-bottom: 2rem;
@@ -626,110 +584,76 @@ onUnmounted(() => {
.operation-category h5 {
color: var(--color-primary);
margin: 0 0 1.5rem 0;
font-size: 1.25rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1.5rem;
font-weight: 700;
padding-bottom: 0.75rem;
border-bottom: 2px solid #f0f0f0;
text-align: center;
}
.operation-blocks {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
.operation-block {
background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
border: 2px solid #e9ecef;
background: white;
border-radius: 12px;
padding: 1.5rem;
text-align: center;
padding: 2rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
border: 1px solid #e9ecef;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.operation-block::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, var(--color-primary), #20c997);
transform: scaleX(0);
transition: transform 0.3s ease;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 200px;
}
.operation-block:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
transform: translateY(-2px);
border-color: var(--color-primary);
box-shadow: 0 8px 25px rgba(0, 123, 255, 0.15);
transform: translateY(-4px);
}
.operation-block:hover::before {
transform: scaleX(1);
}
.operation-icon {
font-size: 3rem;
margin-bottom: 1rem;
display: block;
}
.operation-block h6 {
color: #333;
margin: 0 0 0.75rem 0;
font-size: 1.1rem;
margin: 0 0 1rem 0;
color: var(--color-primary);
font-size: 1.5rem;
font-weight: 600;
flex-shrink: 0;
}
.operation-block p {
color: #666;
margin: 0 0 1.5rem 0;
font-size: 0.9rem;
color: #666;
font-size: 1rem;
line-height: 1.5;
flex-grow: 1;
}
.create-btn {
background: linear-gradient(135deg, var(--color-primary), #20c997);
color: white;
background: var(--color-primary);
color: #fff;
border: none;
border-radius: 8px;
padding: 0.75rem 1.5rem;
cursor: pointer;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
transition: all 0.2s;
min-width: 120px;
width: 100%;
position: relative;
overflow: hidden;
}
.create-btn::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: left 0.5s ease;
flex-shrink: 0;
margin-top: auto;
}
.create-btn:hover {
background: linear-gradient(135deg, #0056b3, #1ea085);
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
background: var(--color-primary-dark);
transform: translateY(-1px);
}
.create-btn:hover::before {
left: 100%;
}
.create-btn:disabled {
background: #6c757d;
cursor: not-allowed;
@@ -737,10 +661,6 @@ onUnmounted(() => {
box-shadow: none;
}
.create-btn:disabled::before {
display: none;
}
/* Стили для модулей */
.module-description {
color: #666;
@@ -751,54 +671,13 @@ onUnmounted(() => {
.module-operation-block {
position: relative;
background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
border: 2px solid #e9ecef;
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 200px;
}
.module-operation-block::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #28a745, #20c997);
transform: scaleX(0);
transition: transform 0.3s ease;
}
.module-operation-block:hover::before {
transform: scaleX(1);
}
.operation-category-tag {
display: inline-block;
background: linear-gradient(135deg, #28a745, #20c997);
color: white;
padding: 0.25rem 0.75rem;
border-radius: 20px;
font-size: 0.75rem;
font-weight: 600;
margin: 0.5rem 0;
text-transform: uppercase;
letter-spacing: 0.5px;
}
/* Анимация появления модулей */
.operation-category {
animation: fadeInUp 0.6s ease-out;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Индикатор загрузки модулей */
.loading-modules {
@@ -828,10 +707,6 @@ onUnmounted(() => {
/* Адаптивность */
@media (max-width: 768px) {
.operations-blocks {
padding: 1rem;
}
.operation-blocks {
grid-template-columns: 1fr;
}
@@ -840,14 +715,6 @@ onUnmounted(() => {
padding: 1rem;
}
.operation-icon {
font-size: 2.5rem;
}
.blocks-header h4 {
font-size: 1.25rem;
}
.operation-category h5 {
font-size: 1.1rem;
}

View File

@@ -32,42 +32,30 @@
<!-- Блоки управления -->
<div class="management-blocks">
<!-- Первый ряд -->
<div class="blocks-row">
<div class="management-block create-proposal-block">
<!-- Столбец 1 -->
<div class="blocks-column">
<div class="management-block">
<h3>Создать предложение</h3>
<p>Универсальная форма для создания новых предложений</p>
<button class="details-btn create-btn" @click="openCreateProposal">
<button class="details-btn" @click="openCreateProposal">
Подробнее
</button>
</div>
<div class="management-block">
<h3>Предложения</h3>
<p>Создание, подписание, выполнение</p>
<button class="details-btn" @click="openProposals">Подробнее</button>
</div>
<div class="management-block">
<h3>Токены DLE</h3>
<p>Балансы, трансферы, распределение</p>
<button class="details-btn" @click="openTokens">Подробнее</button>
</div>
</div>
<!-- Второй ряд -->
<div class="blocks-row">
<div class="management-block">
<h3>Кворум</h3>
<p>Настройки голосования</p>
<button class="details-btn" @click="openQuorum">Подробнее</button>
</div>
<div class="management-block">
<h3>Модули DLE</h3>
<p>Установка, настройка, управление</p>
<button class="details-btn" @click="openModules">Подробнее</button>
</div>
</div>
<!-- Столбец 2 -->
<div class="blocks-column">
<div class="management-block">
<h3>Предложения</h3>
<p>Создание, подписание, выполнение</p>
<button class="details-btn" @click="openProposals">Подробнее</button>
</div>
<div class="management-block">
<h3>Аналитика</h3>
@@ -76,8 +64,8 @@
</div>
</div>
<!-- Третий ряд -->
<div class="blocks-row">
<!-- Столбец 3 -->
<div class="blocks-column">
<div class="management-block">
<h3>История</h3>
<p>Лог операций, события, транзакции</p>
@@ -125,21 +113,6 @@ const openProposals = () => {
}
};
const openTokens = () => {
if (dleAddress.value) {
router.push(`/management/tokens?address=${dleAddress.value}`);
} else {
router.push('/management/tokens');
}
};
const openQuorum = () => {
if (dleAddress.value) {
router.push(`/management/quorum?address=${dleAddress.value}`);
} else {
router.push('/management/quorum');
}
};
const openModules = () => {
if (dleAddress.value) {
@@ -236,15 +209,16 @@ onMounted(() => {
}
.management-blocks {
display: flex;
flex-direction: column;
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2rem;
}
.blocks-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
.blocks-column {
display: flex;
flex-direction: column;
gap: 1.5rem;
align-items: stretch;
}
.management-block {
@@ -255,6 +229,10 @@ onMounted(() => {
border: 1px solid #e9ecef;
transition: all 0.3s ease;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-between;
height: 250px;
}
.management-block:hover {
@@ -268,6 +246,7 @@ onMounted(() => {
color: var(--color-primary);
font-size: 1.5rem;
font-weight: 600;
flex-shrink: 0;
}
.management-block p {
@@ -275,6 +254,7 @@ onMounted(() => {
color: #666;
font-size: 1rem;
line-height: 1.5;
flex-grow: 1;
}
.details-btn {
@@ -288,6 +268,8 @@ onMounted(() => {
font-weight: 600;
transition: all 0.2s;
min-width: 120px;
flex-shrink: 0;
margin-top: auto;
}
.details-btn:hover {
@@ -295,35 +277,16 @@ onMounted(() => {
transform: translateY(-1px);
}
/* Стили для блока создания предложения */
.create-proposal-block {
background: linear-gradient(135deg, #e8f5e8 0%, #f0f8f0 100%);
border: 2px solid #28a745;
}
.create-proposal-block:hover {
border-color: #20c997;
box-shadow: 0 4px 20px rgba(40, 167, 69, 0.15);
}
.create-proposal-block h3 {
color: #28a745;
}
.create-btn {
background: linear-gradient(135deg, #28a745, #20c997);
color: white;
font-weight: 700;
}
.create-btn:hover {
background: linear-gradient(135deg, #218838, #1ea085);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}
/* Адаптивность */
@media (max-width: 1024px) {
.management-blocks {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 768px) {
.blocks-row {
.management-blocks {
grid-template-columns: 1fr;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,598 +0,0 @@
<!--
Copyright (c) 2024-2025 Тарабанов Александр Викторович
All rights reserved.
This software is proprietary and confidential.
Unauthorized copying, modification, or distribution is prohibited.
For licensing inquiries: info@hb3-accelerator.com
Website: https://hb3-accelerator.com
GitHub: https://github.com/HB3-ACCELERATOR
-->
<template>
<BaseLayout
:is-authenticated="isAuthenticated"
:identities="identities"
:token-balances="tokenBalances"
:is-loading-tokens="isLoadingTokens"
@auth-action-completed="$emit('auth-action-completed')"
>
<div class="quorum-container">
<!-- Заголовок -->
<div class="page-header">
<div class="header-content">
<h1>Кворум</h1>
<p>Настройки голосования и кворума</p>
</div>
<button class="close-btn" @click="goBackToBlocks">×</button>
</div>
<!-- Текущие настройки -->
<div class="current-settings-section">
<h2>Текущие настройки</h2>
<div class="settings-grid">
<div class="setting-card">
<h3>Процент кворума</h3>
<p class="setting-value">{{ currentQuorum }}%</p>
<p class="setting-description">Минимальный процент токенов для принятия решения</p>
</div>
<div class="setting-card">
<h3>Задержка голосования</h3>
<p class="setting-value">{{ votingDelay }} блоков</p>
<p class="setting-description">Время между созданием и началом голосования</p>
</div>
<div class="setting-card">
<h3>Период голосования</h3>
<p class="setting-value">{{ votingPeriod }} блоков</p>
<p class="setting-description">Длительность периода голосования</p>
</div>
<div class="setting-card">
<h3>Порог предложений</h3>
<p class="setting-value">{{ proposalThreshold }} токенов</p>
<p class="setting-description">Минимальное количество токенов для создания предложения</p>
</div>
</div>
</div>
<!-- Изменение настроек -->
<div class="change-settings-section">
<h2>Изменить настройки</h2>
<form @submit.prevent="updateSettings" class="settings-form">
<div class="form-row">
<div class="form-group">
<label for="newQuorum">Новый процент кворума:</label>
<input
id="newQuorum"
v-model="newSettings.quorumPercentage"
type="number"
min="1"
max="100"
placeholder="51"
required
>
<span class="input-hint">% (от 1 до 100)</span>
</div>
<div class="form-group">
<label for="newVotingDelay">Новая задержка голосования:</label>
<input
id="newVotingDelay"
v-model="newSettings.votingDelay"
type="number"
min="0"
placeholder="1"
required
>
<span class="input-hint">блоков</span>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="newVotingPeriod">Новый период голосования:</label>
<input
id="newVotingPeriod"
v-model="newSettings.votingPeriod"
type="number"
min="1"
placeholder="45818"
required
>
<span class="input-hint">блоков (~1 неделя)</span>
</div>
<div class="form-group">
<label for="newProposalThreshold">Новый порог предложений:</label>
<input
id="newProposalThreshold"
v-model="newSettings.proposalThreshold"
type="number"
min="0"
placeholder="100"
required
>
<span class="input-hint">токенов</span>
</div>
</div>
<div class="form-group">
<label for="changeReason">Причина изменения:</label>
<textarea
id="changeReason"
v-model="newSettings.reason"
placeholder="Опишите причину изменения настроек..."
rows="4"
required
></textarea>
</div>
<button type="submit" class="btn-primary" :disabled="isUpdating">
{{ isUpdating ? 'Обновление...' : 'Обновить настройки' }}
</button>
</form>
</div>
<!-- История изменений -->
<div class="history-section">
<h2>История изменений</h2>
<div v-if="settingsHistory.length === 0" class="empty-state">
<p>Нет истории изменений настроек</p>
</div>
<div v-else class="history-list">
<div
v-for="change in settingsHistory"
:key="change.id"
class="history-item"
>
<div class="history-header">
<h3>Изменение #{{ change.id }}</h3>
<span class="change-date">{{ formatDate(change.timestamp) }}</span>
</div>
<div class="change-details">
<p><strong>Причина:</strong> {{ change.reason }}</p>
<div class="changes-list">
<div v-if="change.quorumChange" class="change-item">
<span class="change-label">Кворум:</span>
<span class="change-value">{{ change.quorumChange.from }}% {{ change.quorumChange.to }}%</span>
</div>
<div v-if="change.votingDelayChange" class="change-item">
<span class="change-label">Задержка голосования:</span>
<span class="change-value">{{ change.votingDelayChange.from }} {{ change.votingDelayChange.to }} блоков</span>
</div>
<div v-if="change.votingPeriodChange" class="change-item">
<span class="change-label">Период голосования:</span>
<span class="change-value">{{ change.votingPeriodChange.from }} {{ change.votingPeriodChange.to }} блоков</span>
</div>
<div v-if="change.proposalThresholdChange" class="change-item">
<span class="change-label">Порог предложений:</span>
<span class="change-value">{{ change.proposalThresholdChange.from }} {{ change.proposalThresholdChange.to }} токенов</span>
</div>
</div>
</div>
<div class="change-author">
<span>Автор: {{ formatAddress(change.author) }}</span>
</div>
</div>
</div>
</div>
</div>
</BaseLayout>
</template>
<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import BaseLayout from '../../components/BaseLayout.vue';
import { getGovernanceParams } from '../../services/dleV2Service.js';
import { getQuorumAt, getVotingPowerAt } from '../../services/proposalsService.js';
// Определяем props
const props = defineProps({
isAuthenticated: Boolean,
identities: Array,
tokenBalances: Object,
isLoadingTokens: Boolean
});
// Определяем emits
const emit = defineEmits(['auth-action-completed']);
const router = useRouter();
const route = useRoute();
// Получаем адрес DLE из URL
const dleAddress = computed(() => {
return route.query.address;
});
// Функция возврата к блокам управления
const goBackToBlocks = () => {
if (dleAddress.value) {
router.push(`/management/dle-blocks?address=${dleAddress.value}`);
} else {
router.push('/management');
}
};
// Состояние
const isUpdating = ref(false);
// Текущие настройки
const currentQuorum = ref(51);
const votingDelay = ref(1);
const votingPeriod = ref(45818);
const proposalThreshold = ref(100);
// Новые настройки
const newSettings = ref({
quorumPercentage: '',
votingDelay: '',
votingPeriod: '',
proposalThreshold: '',
reason: ''
});
// История изменений (загружается из блокчейна)
const settingsHistory = ref([]);
// Методы
const updateSettings = async () => {
if (isUpdating.value) return;
try {
isUpdating.value = true;
// Здесь будет логика обновления настроек в смарт-контракте
// console.log('Обновление настроек:', newSettings.value);
// Временная логика
const change = {
id: settingsHistory.value.length + 1,
timestamp: Date.now(),
reason: newSettings.value.reason,
author: '0x' + Math.random().toString(16).substr(2, 40)
};
// Добавляем изменения в историю
if (newSettings.value.quorumPercentage && newSettings.value.quorumPercentage !== currentQuorum.value) {
change.quorumChange = { from: currentQuorum.value, to: parseInt(newSettings.value.quorumPercentage) };
currentQuorum.value = parseInt(newSettings.value.quorumPercentage);
}
if (newSettings.value.votingDelay && newSettings.value.votingDelay !== votingDelay.value) {
change.votingDelayChange = { from: votingDelay.value, to: parseInt(newSettings.value.votingDelay) };
votingDelay.value = parseInt(newSettings.value.votingDelay);
}
if (newSettings.value.votingPeriod && newSettings.value.votingPeriod !== votingPeriod.value) {
change.votingPeriodChange = { from: votingPeriod.value, to: parseInt(newSettings.value.votingPeriod) };
votingPeriod.value = parseInt(newSettings.value.votingPeriod);
}
if (newSettings.value.proposalThreshold && newSettings.value.proposalThreshold !== proposalThreshold.value) {
change.proposalThresholdChange = { from: proposalThreshold.value, to: parseInt(newSettings.value.proposalThreshold) };
proposalThreshold.value = parseInt(newSettings.value.proposalThreshold);
}
settingsHistory.value.unshift(change);
// Сброс формы
newSettings.value = {
quorumPercentage: '',
votingDelay: '',
votingPeriod: '',
proposalThreshold: '',
reason: ''
};
alert('Настройки успешно обновлены!');
} catch (error) {
// console.error('Ошибка обновления настроек:', error);
alert('Ошибка при обновлении настроек');
} finally {
isUpdating.value = false;
}
};
const formatAddress = (address) => {
if (!address) return '';
return address.substring(0, 6) + '...' + address.substring(address.length - 4);
};
const formatDate = (timestamp) => {
return new Date(timestamp).toLocaleString('ru-RU');
};
</script>
<style scoped>
.quorum-container {
padding: 20px;
background-color: var(--color-white);
border-radius: var(--radius-lg);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-top: 20px;
margin-bottom: 20px;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 2px solid #f0f0f0;
}
.header-content {
flex-grow: 1;
}
.page-header h1 {
color: var(--color-primary);
font-size: 2.5rem;
margin: 0 0 10px 0;
}
.page-header p {
color: var(--color-grey-dark);
font-size: 1.1rem;
margin: 0;
}
.close-btn {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
padding: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
transition: all 0.2s;
flex-shrink: 0;
}
.close-btn:hover {
background: #f0f0f0;
color: #333;
}
/* Секции */
.current-settings-section,
.change-settings-section,
.history-section {
margin-bottom: 40px;
}
.current-settings-section h2,
.change-settings-section h2,
.history-section h2 {
color: var(--color-primary);
margin-bottom: 20px;
font-size: 1.8rem;
}
/* Текущие настройки */
.settings-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
}
.setting-card {
background: #f8f9fa;
padding: 25px;
border-radius: var(--radius-lg);
border-left: 4px solid var(--color-primary);
}
.setting-card h3 {
color: var(--color-primary);
margin-bottom: 15px;
font-size: 1.1rem;
font-weight: 600;
}
.setting-value {
font-size: 1.8rem;
font-weight: 700;
margin: 0 0 10px 0;
color: var(--color-primary);
}
.setting-description {
font-size: 0.9rem;
color: var(--color-grey-dark);
margin: 0;
line-height: 1.4;
}
/* Форма настроек */
.settings-form {
background: #f8f9fa;
padding: 25px;
border-radius: var(--radius-lg);
border: 1px solid #e9ecef;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 20px;
}
.form-group label {
font-weight: 600;
color: var(--color-grey-dark);
}
.form-group input,
.form-group textarea {
padding: 12px;
border: 1px solid #ddd;
border-radius: var(--radius-sm);
font-size: 1rem;
}
.form-group textarea {
resize: vertical;
min-height: 100px;
}
.input-hint {
font-size: 0.8rem;
color: var(--color-grey-dark);
margin-top: 4px;
}
/* История изменений */
.history-list {
display: grid;
gap: 20px;
}
.history-item {
background: white;
padding: 25px;
border-radius: var(--radius-lg);
border: 1px solid #e9ecef;
transition: all 0.3s ease;
}
.history-item:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.history-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.history-header h3 {
margin: 0;
color: var(--color-primary);
font-size: 1.2rem;
}
.change-date {
font-size: 0.9rem;
color: var(--color-grey-dark);
}
.change-details {
margin-bottom: 15px;
}
.change-details p {
margin: 0 0 15px 0;
font-size: 0.95rem;
}
.changes-list {
display: grid;
gap: 8px;
}
.change-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
background: #f8f9fa;
border-radius: var(--radius-sm);
}
.change-label {
font-weight: 600;
color: var(--color-grey-dark);
font-size: 0.9rem;
}
.change-value {
font-weight: 600;
color: var(--color-primary);
font-size: 0.9rem;
}
.change-author {
font-size: 0.8rem;
color: var(--color-grey-dark);
font-family: monospace;
}
/* Кнопки */
.btn-primary {
background: var(--color-primary);
color: white;
border: none;
padding: 12px 24px;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 1rem;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-primary:hover:not(:disabled) {
background: var(--color-primary-dark);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* Состояния */
.empty-state {
text-align: center;
padding: 60px;
color: var(--color-grey-dark);
background: #f8f9fa;
border-radius: var(--radius-lg);
border: 2px dashed #dee2e6;
}
.empty-state p {
margin: 0;
font-size: 1.1rem;
}
/* Адаптивность */
@media (max-width: 768px) {
.form-row {
grid-template-columns: 1fr;
}
.history-header {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.change-item {
flex-direction: column;
align-items: flex-start;
gap: 5px;
}
.settings-grid {
grid-template-columns: 1fr;
}
}
</style>

View File

@@ -1,740 +0,0 @@
<!--
Copyright (c) 2024-2025 Тарабанов Александр Викторович
All rights reserved.
This software is proprietary and confidential.
Unauthorized copying, modification, or distribution is prohibited.
For licensing inquiries: info@hb3-accelerator.com
Website: https://hb3-accelerator.com
GitHub: https://github.com/HB3-ACCELERATOR
-->
<template>
<BaseLayout
:is-authenticated="isAuthenticated"
:identities="identities"
:token-balances="tokenBalances"
:is-loading-tokens="isLoadingTokens"
@auth-action-completed="$emit('auth-action-completed')"
>
<div class="tokens-container">
<!-- Заголовок -->
<div class="page-header">
<div class="header-content">
<h1>Управление токенами DLE</h1>
<p>Создание предложений для перевода токенов через систему голосования</p>
<div v-if="selectedDle" class="dle-info">
<span class="dle-name">{{ selectedDle.name }} ({{ selectedDle.symbol }})</span>
<span class="dle-address">{{ shortenAddress(selectedDle.dleAddress) }}</span>
</div>
<div v-else-if="isLoadingDle" class="loading-info">
<span>Загрузка данных DLE...</span>
</div>
<div v-else class="no-dle-info">
<span>DLE не выбран</span>
</div>
</div>
<button class="close-btn" @click="goBackToBlocks">×</button>
</div>
<!-- Информация о токенах -->
<div class="token-info-section">
<h2>Информация о токенах</h2>
<div class="token-info-grid">
<div class="info-card">
<h3>Общий запас</h3>
<p class="token-amount">{{ totalSupply }} {{ tokenSymbol }}</p>
</div>
<div class="info-card">
<h3>Ваш баланс</h3>
<p class="token-amount">{{ userBalance }} {{ tokenSymbol }}</p>
<p v-if="currentUserAddress" class="user-address">{{ shortenAddress(currentUserAddress) }}</p>
<p v-else class="no-wallet">Кошелек не подключен</p>
</div>
<div class="info-card">
<h3>Цена токена</h3>
<p class="token-amount">${{ tokenPrice }}</p>
</div>
</div>
</div>
<!-- Перевод токенов через governance -->
<div class="transfer-section">
<h2>Перевод токенов через Governance</h2>
<p class="section-description">
Создайте предложение для перевода токенов через систему голосования.
Токены будут переведены от имени DLE после одобрения кворумом.
<strong>Важно:</strong> Перевод через governance будет выполнен во всех поддерживаемых сетях DLE.
</p>
<form @submit.prevent="createTransferProposal" class="transfer-form">
<div class="form-group">
<label for="proposal-recipient">Адрес получателя:</label>
<input
id="proposal-recipient"
v-model="proposalData.recipient"
type="text"
placeholder="0x..."
required
/>
</div>
<div class="form-group">
<label for="proposal-amount">Количество токенов:</label>
<input
id="proposal-amount"
v-model="proposalData.amount"
type="number"
step="0.000001"
placeholder="0.0"
required
/>
</div>
<div class="form-group">
<label for="proposal-description">Описание предложения:</label>
<textarea
id="proposal-description"
v-model="proposalData.description"
placeholder="Опишите причину перевода токенов..."
required
></textarea>
</div>
<div class="form-group">
<label for="proposal-duration">Длительность голосования (часы):</label>
<input
id="proposal-duration"
v-model="proposalData.duration"
type="number"
min="1"
max="168"
placeholder="24"
required
/>
</div>
<button type="submit" class="btn-primary" :disabled="isCreatingProposal">
{{ isCreatingProposal ? 'Создание предложения...' : 'Создать предложение' }}
</button>
<!-- Статус предложения -->
<div v-if="proposalStatus" class="proposal-status">
<p class="status-message">{{ proposalStatus }}</p>
</div>
</form>
</div>
<!-- Держатели токенов -->
<div class="holders-section">
<h2>Держатели токенов</h2>
<div v-if="tokenHolders.length === 0" class="empty-state">
<p>Нет данных о держателях токенов</p>
</div>
<div v-else class="holders-list">
<div
v-for="holder in tokenHolders"
:key="holder.address"
class="holder-item"
>
<div class="holder-info">
<span class="holder-address">{{ formatAddress(holder.address) }}</span>
<span class="holder-balance">{{ holder.balance }} {{ tokenSymbol }}</span>
</div>
<div class="holder-percentage">
{{ ((holder.balance / totalSupply) * 100).toFixed(2) }}%
</div>
</div>
</div>
</div>
</div>
</BaseLayout>
</template>
<script setup>
import { ref, computed, onMounted, watch, defineProps, defineEmits } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import BaseLayout from '../../components/BaseLayout.vue';
import { getTokenBalance, getTotalSupply, getTokenHolders } from '../../services/tokensService.js';
import api from '../../api/axios';
import { ethers } from 'ethers';
import { createTransferTokensProposal } from '../../utils/dle-contract.js';
// Определяем props
const props = defineProps({
isAuthenticated: Boolean,
identities: Array,
tokenBalances: Object,
isLoadingTokens: Boolean
});
// Определяем emits
const emit = defineEmits(['auth-action-completed']);
const router = useRouter();
const route = useRoute();
// Получаем адрес DLE из URL
const dleAddress = computed(() => {
const address = route.query.address;
console.log('DLE Address from URL (Tokens):', address);
return address;
});
// Функция возврата к блокам управления
const goBackToBlocks = () => {
if (dleAddress.value) {
router.push(`/management/dle-blocks?address=${dleAddress.value}`);
} else {
router.push('/management');
}
};
// Состояние DLE
const selectedDle = ref(null);
const isLoadingDle = ref(false);
// Состояние для предложения о переводе токенов через governance
const isCreatingProposal = ref(false);
const proposalStatus = ref('');
// Данные токенов (загружаются из блокчейна)
const totalSupply = ref(0);
const userBalance = ref(0);
const deployerBalance = ref(0);
const quorumPercentage = ref(0);
const tokenPrice = ref(0);
// Данные для формы
const proposalData = ref({
recipient: '',
amount: '',
description: '',
duration: 86400, // 24 часа по умолчанию
governanceChainId: 11155111, // Sepolia по умолчанию
targetChains: [11155111] // Sepolia по умолчанию
});
// Получаем адрес текущего пользователя
const currentUserAddress = computed(() => {
console.log('Проверяем identities:', props.identities);
// Получаем адрес из props или из window.ethereum
if (props.identities && props.identities.length > 0) {
const walletIdentity = props.identities.find(id => id.provider === 'wallet');
console.log('Найден wallet identity:', walletIdentity);
if (walletIdentity) {
return walletIdentity.provider_id;
}
}
// Fallback: пытаемся получить из window.ethereum
if (window.ethereum && window.ethereum.selectedAddress) {
console.log('Получаем адрес из window.ethereum:', window.ethereum.selectedAddress);
return window.ethereum.selectedAddress;
}
console.log('Адрес пользователя не найден');
return null;
});
// Держатели токенов (загружаются из блокчейна)
const tokenHolders = ref([]);
// Функции
async function loadDleData() {
if (!dleAddress.value) {
console.warn('Адрес DLE не указан');
return;
}
isLoadingDle.value = true;
try {
// Читаем актуальные данные из блокчейна
const response = await api.post('/dle-core/read-dle-info', {
dleAddress: dleAddress.value
});
if (response.data.success) {
const blockchainData = response.data.data;
selectedDle.value = blockchainData;
console.log('Загружены данные DLE из блокчейна:', blockchainData);
// Загружаем баланс текущего пользователя
await loadUserBalance();
// Загружаем держателей токенов (если есть API)
await loadTokenHolders();
} else {
console.warn('Не удалось прочитать данные из блокчейна для', dleAddress.value);
}
} catch (error) {
console.error('Ошибка загрузки данных DLE из блокчейна:', error);
} finally {
isLoadingDle.value = false;
}
}
// Новая функция для загрузки баланса текущего пользователя
async function loadUserBalance() {
if (!currentUserAddress.value || !dleAddress.value) {
userBalance.value = 0;
console.log('Не удается загрузить баланс: нет адреса пользователя или DLE');
return;
}
try {
console.log('Загружаем баланс для пользователя:', currentUserAddress.value);
const response = await api.post('/blockchain/get-token-balance', {
dleAddress: dleAddress.value,
account: currentUserAddress.value
});
if (response.data.success) {
userBalance.value = parseFloat(response.data.data.balance);
console.log('Баланс пользователя загружен:', userBalance.value);
} else {
console.warn('Не удалось загрузить баланс пользователя:', response.data.error);
userBalance.value = 0;
}
} catch (error) {
console.error('Ошибка загрузки баланса пользователя:', error);
userBalance.value = 0;
}
}
async function loadTokenHolders() {
try {
// Здесь можно добавить загрузку держателей токенов из блокчейна
// Пока оставляем пустым
tokenHolders.value = [];
} catch (error) {
console.error('Ошибка загрузки держателей токенов:', error);
}
}
function shortenAddress(address) {
if (!address) return '';
return `${address.slice(0, 6)}...${address.slice(-4)}`;
}
// Методы
const formatAddress = (address) => {
if (!address) return '';
return address.substring(0, 6) + '...' + address.substring(address.length - 4);
};
// Функция создания предложения о переводе токенов через governance
const createTransferProposal = async () => {
if (isCreatingProposal.value) return;
try {
// Проверяем подключение к кошельку
if (!window.ethereum) {
alert('Пожалуйста, установите MetaMask или другой Web3 кошелек');
return;
}
// Проверяем, что пользователь подключен
if (!currentUserAddress.value) {
alert('Пожалуйста, подключите кошелек');
return;
}
// Валидация данных
const recipient = proposalData.value.recipient.trim();
const amount = parseFloat(proposalData.value.amount);
const description = proposalData.value.description.trim();
if (!recipient) {
alert('Пожалуйста, укажите адрес получателя');
return;
}
// Проверяем, что адрес получателя является корректным Ethereum адресом
if (!ethers.isAddress(recipient)) {
alert('Пожалуйста, укажите корректный Ethereum адрес получателя');
return;
}
if (!amount || amount <= 0) {
alert('Пожалуйста, укажите корректное количество токенов');
return;
}
if (!description) {
alert('Пожалуйста, укажите описание предложения');
return;
}
// Проверяем, что получатель не является отправителем
if (recipient.toLowerCase() === currentUserAddress.value.toLowerCase()) {
alert('Нельзя отправить токены самому себе');
return;
}
isCreatingProposal.value = true;
proposalStatus.value = 'Создание предложения...';
// Создаем предложение
const result = await createTransferTokensProposal(dleAddress.value, {
recipient: recipient,
amount: amount,
description: description,
duration: proposalData.value.duration * 3600, // Конвертируем часы в секунды
governanceChainId: proposalData.value.governanceChainId,
targetChains: proposalData.value.targetChains
});
proposalStatus.value = 'Предложение создано!';
console.log('Предложение о переводе токенов создано:', result);
// Сброс формы
proposalData.value = {
recipient: '',
amount: '',
description: '',
duration: 86400,
governanceChainId: 11155111,
targetChains: [11155111]
};
// Очищаем статус через 5 секунд
setTimeout(() => {
proposalStatus.value = '';
}, 5000);
alert(`Предложение о переводе токенов создано!\nID предложения: ${result.proposalId}\nХеш транзакции: ${result.txHash}`);
} catch (error) {
console.error('Ошибка создания предложения о переводе токенов:', error);
// Очищаем статус предложения
proposalStatus.value = '';
let errorMessage = 'Ошибка создания предложения о переводе токенов';
if (error.code === 4001) {
errorMessage = 'Транзакция отменена пользователем';
} else if (error.message && error.message.includes('insufficient funds')) {
errorMessage = 'Недостаточно ETH для оплаты газа';
} else if (error.message && error.message.includes('execution reverted')) {
errorMessage = 'Ошибка выполнения транзакции. Проверьте данные и попробуйте снова';
} else if (error.message) {
errorMessage = error.message;
}
alert(errorMessage);
} finally {
isCreatingProposal.value = false;
}
};
// Отслеживаем изменения в адресе DLE
watch(dleAddress, (newAddress) => {
if (newAddress) {
loadDleData();
}
}, { immediate: true });
// Отслеживаем изменения адреса пользователя
watch(currentUserAddress, (newAddress) => {
if (newAddress && dleAddress.value) {
loadUserBalance();
} else {
userBalance.value = 0;
}
}, { immediate: true });
</script>
<style scoped>
.tokens-container {
padding: 20px;
background-color: var(--color-white);
border-radius: var(--radius-lg);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-top: 20px;
margin-bottom: 20px;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 2px solid #f0f0f0;
}
.header-content {
flex-grow: 1;
}
.page-header h1 {
color: var(--color-primary);
font-size: 2.5rem;
margin: 0 0 10px 0;
}
.page-header p {
color: var(--color-grey-dark);
font-size: 1.1rem;
margin: 0;
}
.dle-info {
display: flex;
flex-direction: column;
gap: 0.25rem;
margin-top: 0.5rem;
}
.dle-name {
font-weight: 600;
color: #333;
font-size: 1rem;
}
.dle-address {
font-family: monospace;
font-size: 0.875rem;
color: #666;
background: #f8f9fa;
padding: 0.25rem 0.5rem;
border-radius: 4px;
display: inline-block;
width: fit-content;
}
.loading-info,
.no-dle-info {
font-size: 0.875rem;
color: #666;
font-style: italic;
margin-top: 0.5rem;
}
.close-btn {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
padding: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
transition: all 0.2s;
flex-shrink: 0;
}
.close-btn:hover {
background: #f0f0f0;
color: #333;
}
/* Секции */
.token-info-section,
.transfer-section,
.holders-section {
margin-bottom: 40px;
}
.token-info-section h2,
.transfer-section h2,
.holders-section h2 {
color: var(--color-primary);
margin-bottom: 20px;
font-size: 1.8rem;
}
/* Информация о токенах */
.token-info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.info-card {
background: #f8f9fa;
padding: 25px;
border-radius: var(--radius-lg);
border-left: 4px solid var(--color-primary);
text-align: center;
}
.info-card h3 {
color: var(--color-primary);
margin-bottom: 15px;
font-size: 1rem;
text-transform: uppercase;
font-weight: 600;
}
.token-amount {
font-size: 1.8rem;
font-weight: 700;
margin: 0;
color: var(--color-primary);
}
.user-address {
font-family: monospace;
font-size: 0.75rem;
color: #666;
margin: 5px 0 0 0;
background: #f8f9fa;
padding: 2px 6px;
border-radius: 3px;
display: inline-block;
}
.no-wallet {
font-size: 0.75rem;
color: #dc3545;
margin: 5px 0 0 0;
font-style: italic;
}
/* Формы */
.transfer-form {
background: #f8f9fa;
padding: 25px;
border-radius: var(--radius-lg);
border: 1px solid #e9ecef;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 20px;
}
.form-group label {
font-weight: 600;
color: var(--color-grey-dark);
}
.form-group input,
.form-group select,
.form-group textarea {
padding: 12px;
border: 1px solid #ddd;
border-radius: var(--radius-sm);
font-size: 1rem;
}
.form-group textarea {
resize: vertical;
min-height: 80px;
}
/* Статус предложения */
.proposal-status {
margin-top: 20px;
padding: 15px;
background: #e8f5e8;
border-radius: var(--radius-sm);
border-left: 4px solid #28a745;
}
.proposal-status .status-message {
color: #28a745;
}
/* Описание секции */
.section-description {
color: var(--color-grey-dark);
font-size: 0.95rem;
margin-bottom: 20px;
line-height: 1.5;
}
/* Кнопки */
.btn-primary {
background: var(--color-primary);
color: white;
border: none;
padding: 12px 24px;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 1rem;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-primary:hover:not(:disabled) {
background: var(--color-primary-dark);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-secondary {
background: var(--color-secondary);
color: white;
border: none;
padding: 10px 20px;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.9rem;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-secondary:hover {
background: var(--color-secondary-dark);
}
/* Состояния */
.empty-state {
text-align: center;
padding: 60px;
color: var(--color-grey-dark);
background: #f8f9fa;
border-radius: var(--radius-lg);
border: 2px dashed #dee2e6;
}
.empty-state p {
margin: 0;
font-size: 1.1rem;
}
/* Адаптивность */
@media (max-width: 768px) {
.form-row {
grid-template-columns: 1fr;
}
.recipient-item {
grid-template-columns: 1fr;
gap: 10px;
}
.holder-item {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.token-info-grid {
grid-template-columns: 1fr;
}
}
</style>