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

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

@@ -0,0 +1,31 @@
#!/usr/bin/env node
/**
* Скрипт для очистки кэша формы деплоя
* Удаляет localStorage данные, чтобы форма использовала свежие данные
*/
console.log('🧹 Очистка кэша формы деплоя...');
// Инструкции для пользователя
console.log(`
📋 ИНСТРУКЦИИ ДЛЯ ОЧИСТКИ КЭША:
1. Откройте браузер и перейдите на http://localhost:5173
2. Откройте Developer Tools (F12)
3. Перейдите во вкладку "Application" или "Storage"
4. Найдите "Local Storage" -> "http://localhost:5173"
5. Найдите ключ "dle_form_data" и удалите его
6. Или выполните в консоли браузера:
localStorage.removeItem('dle_form_data');
7. Перезагрузите страницу (F5)
🔧 АЛЬТЕРНАТИВНО - можно добавить кнопку "Очистить кэш" в форму:
- Добавить кнопку в DleDeployFormView.vue
- При клике выполнять: localStorage.removeItem('dle_form_data');
- Перезагружать страницу
✅ После очистки кэша форма будет использовать свежие данные
`);
console.log('🏁 Инструкции выведены. Выполните очистку кэша в браузере.');

View File

@@ -1,78 +0,0 @@
{
"deploymentId": "modules-deploy-1758801398489",
"dleAddress": "0x40A99dBEC8D160a226E856d370dA4f3C67713940",
"dleName": "DLE Test",
"dleSymbol": "TOKEN",
"dleLocation": "101000, Москва, Москва, Тверская, 1, 101",
"dleJurisdiction": 643,
"dleCoordinates": "55.7614035,37.6342935",
"dleOktmo": "45000000",
"dleOkvedCodes": [
"62.01",
"63.11"
],
"dleKpp": "773009001",
"dleLogoURI": "/uploads/logos/default-token.svg",
"dleSupportedChainIds": [
11155111,
17000,
421614,
84532
],
"totalNetworks": 4,
"successfulNetworks": 4,
"modulesDeployed": [
"reader"
],
"networks": [
{
"chainId": 17000,
"rpcUrl": "https://ethereum-holesky.publicnode.com",
"modules": [
{
"type": "reader",
"address": "0x1bA03A5f814d3781984D0f7Bca0E8E74c5e47545",
"success": true,
"verification": "success"
}
]
},
{
"chainId": 84532,
"rpcUrl": "https://sepolia.base.org",
"modules": [
{
"type": "reader",
"address": "0x1bA03A5f814d3781984D0f7Bca0E8E74c5e47545",
"success": true,
"verification": "success"
}
]
},
{
"chainId": 421614,
"rpcUrl": "https://sepolia-rollup.arbitrum.io/rpc",
"modules": [
{
"type": "reader",
"address": "0x1bA03A5f814d3781984D0f7Bca0E8E74c5e47545",
"success": true,
"verification": "success"
}
]
},
{
"chainId": 11155111,
"rpcUrl": "https://1rpc.io/sepolia",
"modules": [
{
"type": "reader",
"address": "0x1bA03A5f814d3781984D0f7Bca0E8E74c5e47545",
"success": true,
"verification": "success"
}
]
}
],
"timestamp": "2025-09-25T11:56:38.490Z"
}

View File

@@ -14,27 +14,13 @@
const hre = require('hardhat');
const path = require('path');
const fs = require('fs');
const logger = require('../../utils/logger');
const { getFeeOverrides, createProviderAndWallet, alignNonce, getNetworkInfo, createRPCConnection, sendTransactionWithRetry } = require('../../utils/deploymentUtils');
const { nonceManager } = require('../../utils/nonceManager');
// WebSocket сервис для отслеживания деплоя
const deploymentWebSocketService = require('../../services/deploymentWebSocketService');
// Подбираем безопасные gas/fee для разных сетей (включая L2)
async function getFeeOverrides(provider, { minPriorityGwei = 1n, minFeeGwei = 20n } = {}) {
const fee = await provider.getFeeData();
const overrides = {};
const minPriority = (await (async () => hre.ethers.parseUnits(minPriorityGwei.toString(), 'gwei'))());
const minFee = (await (async () => hre.ethers.parseUnits(minFeeGwei.toString(), 'gwei'))());
if (fee.maxFeePerGas) {
overrides.maxFeePerGas = fee.maxFeePerGas < minFee ? minFee : fee.maxFeePerGas;
overrides.maxPriorityFeePerGas = (fee.maxPriorityFeePerGas && fee.maxPriorityFeePerGas > 0n)
? fee.maxPriorityFeePerGas
: minPriority;
} else if (fee.gasPrice) {
overrides.gasPrice = fee.gasPrice < minFee ? minFee : fee.gasPrice;
}
return overrides;
}
// Конфигурация модулей для деплоя
const MODULE_CONFIGS = {
treasury: {
@@ -88,22 +74,29 @@ const MODULE_CONFIGS = {
// Деплой модуля в одной сети с CREATE2
async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce, moduleInit, moduleType) {
const { ethers } = hre;
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(pk, provider);
const net = await provider.getNetwork();
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} deploying ${moduleType}...`);
// 1) Выравнивание nonce до targetNonce нулевыми транзакциями (если нужно)
let current = await provider.getTransactionCount(wallet.address, 'pending');
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} current nonce=${current} target=${targetNonce}`);
// Используем новый менеджер RPC с retry логикой
const { provider, wallet, network } = await createRPCConnection(rpcUrl, pk, {
maxRetries: 3,
timeout: 30000
});
const net = network;
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} deploying ${moduleType}...`);
// 1) Используем NonceManager для правильного управления nonce
const { nonceManager } = require('../../utils/nonceManager');
const chainId = Number(net.chainId);
let current = await nonceManager.getNonce(wallet.address, rpcUrl, chainId);
logger.info(`[MODULES_DBG] chainId=${chainId} current nonce=${current} target=${targetNonce}`);
if (current > targetNonce) {
throw new Error(`Current nonce ${current} > targetNonce ${targetNonce} on chainId=${Number(net.chainId)}`);
}
if (current < targetNonce) {
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} aligning nonce from ${current} to ${targetNonce} (${targetNonce - current} transactions needed)`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} aligning nonce from ${current} to ${targetNonce} (${targetNonce - current} transactions needed)`);
// Используем burn address для более надежных транзакций
const burnAddress = "0x000000000000000000000000000000000000dEaD";
@@ -123,15 +116,14 @@ async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce
gasLimit,
...overrides
};
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} sending filler tx nonce=${current} attempt=${attempt + 1}`);
const txFill = await wallet.sendTransaction(txReq);
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx sent, hash=${txFill.hash}, waiting for confirmation...`);
await txFill.wait();
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} confirmed, hash=${txFill.hash}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} sending filler tx nonce=${current} attempt=${attempt + 1}`);
const { tx: txFill, receipt } = await sendTransactionWithRetry(wallet, txReq, { maxRetries: 3 });
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx sent, hash=${txFill.hash}, waiting for confirmation...`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} confirmed, hash=${txFill.hash}`);
sent = true;
} catch (e) {
lastErr = e;
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} attempt=${attempt + 1} failed: ${e?.message || e}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} attempt=${attempt + 1} failed: ${e?.message || e}`);
if (String(e?.message || '').toLowerCase().includes('intrinsic gas too low') && attempt < 2) {
gasLimit = 50000;
@@ -139,8 +131,17 @@ async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce
}
if (String(e?.message || '').toLowerCase().includes('nonce too low') && attempt < 2) {
// Сбрасываем кэш и получаем актуальный nonce
const { nonceManager } = require('../../utils/nonceManager');
nonceManager.resetNonce(wallet.address, Number(net.chainId));
current = await provider.getTransactionCount(wallet.address, 'pending');
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} updated nonce to ${current}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} updated nonce to ${current}`);
// Если новый nonce больше целевого, это критическая ошибка
if (current > targetNonce) {
throw new Error(`Current nonce ${current} > target nonce ${targetNonce} on chainId=${Number(net.chainId)}. Cannot proceed with module deployment.`);
}
continue;
}
@@ -149,20 +150,20 @@ async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce
}
if (!sent) {
console.error(`[MODULES_DBG] chainId=${Number(net.chainId)} failed to send filler tx for nonce=${current}`);
logger.error(`[MODULES_DBG] chainId=${Number(net.chainId)} failed to send filler tx for nonce=${current}`);
throw lastErr || new Error('filler tx failed');
}
current++;
}
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} nonce alignment completed, current nonce=${current}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} nonce alignment completed, current nonce=${current}`);
} else {
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} nonce already aligned at ${current}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} nonce already aligned at ${current}`);
}
// 2) Деплой модуля напрямую на согласованном nonce
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} deploying ${moduleType} directly with nonce=${targetNonce}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} deploying ${moduleType} directly with nonce=${targetNonce}`);
const feeOverrides = await getFeeOverrides(provider);
let gasLimit;
@@ -179,7 +180,7 @@ async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce
const fallbackGas = maxByBalance > 2_000_000n ? 2_000_000n : (maxByBalance < 500_000n ? 500_000n : maxByBalance);
gasLimit = est ? (est + est / 5n) : fallbackGas;
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} estGas=${est?.toString?.()||'null'} effGasPrice=${effPrice?.toString?.()||'0'} maxByBalance=${maxByBalance.toString()} chosenGasLimit=${gasLimit.toString()}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} estGas=${est?.toString?.()||'null'} effGasPrice=${effPrice?.toString?.()||'0'} maxByBalance=${maxByBalance.toString()} chosenGasLimit=${gasLimit.toString()}`);
} catch (_) {
gasLimit = 1_000_000n;
}
@@ -189,41 +190,115 @@ async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce
from: wallet.address,
nonce: targetNonce
});
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} predicted ${moduleType} address=${predictedAddress}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} predicted ${moduleType} address=${predictedAddress}`);
// Проверяем, не развернут ли уже контракт
const existingCode = await provider.getCode(predictedAddress);
if (existingCode && existingCode !== '0x') {
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} ${moduleType} already exists at predictedAddress, skip deploy`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} ${moduleType} already exists at predictedAddress, skip deploy`);
return { address: predictedAddress, chainId: Number(net.chainId) };
}
// Деплоим модуль
// Деплоим модуль с retry логикой для обработки race conditions
let tx;
try {
tx = await wallet.sendTransaction({
data: moduleInit,
nonce: targetNonce,
gasLimit,
...feeOverrides
});
} catch (e) {
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} deploy error(first): ${e?.message || e}`);
// Повторная попытка с обновленным nonce
const updatedNonce = await provider.getTransactionCount(wallet.address, 'pending');
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} retry deploy with nonce=${updatedNonce}`);
tx = await wallet.sendTransaction({
data: moduleInit,
nonce: updatedNonce,
gasLimit,
...feeOverrides
});
let deployAttempts = 0;
const maxDeployAttempts = 5;
while (deployAttempts < maxDeployAttempts) {
try {
deployAttempts++;
// Получаем актуальный nonce прямо перед отправкой транзакции
const currentNonce = await nonceManager.getNonce(wallet.address, rpcUrl, Number(net.chainId), { timeout: 15000, maxRetries: 5 });
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} deploy attempt ${deployAttempts}/${maxDeployAttempts} with current nonce=${currentNonce} (target was ${targetNonce})`);
const txData = {
data: moduleInit,
nonce: currentNonce,
gasLimit,
...feeOverrides
};
const result = await sendTransactionWithRetry(wallet, txData, { maxRetries: 3 });
tx = result.tx;
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} deploy successful on attempt ${deployAttempts}`);
break; // Успешно отправили, выходим из цикла
} catch (e) {
const errorMsg = e?.message || e;
logger.warn(`[MODULES_DBG] chainId=${Number(net.chainId)} deploy attempt ${deployAttempts} failed: ${errorMsg}`);
// Проверяем, является ли это ошибкой nonce
if (String(errorMsg).toLowerCase().includes('nonce too low') && deployAttempts < maxDeployAttempts) {
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} nonce race condition detected, retrying...`);
// Получаем актуальный nonce из сети
const currentNonce = await nonceManager.getNonce(wallet.address, rpcUrl, Number(net.chainId), { timeout: 15000, maxRetries: 5 });
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} current nonce: ${currentNonce}, target: ${targetNonce}`);
// Если текущий nonce больше целевого, обновляем targetNonce
if (currentNonce > targetNonce) {
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} current nonce ${currentNonce} > target nonce ${targetNonce}, updating target`);
targetNonce = currentNonce;
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} updated targetNonce to: ${targetNonce}`);
// Короткая задержка перед следующей попыткой
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
// Если текущий nonce меньше целевого, выравниваем его
if (currentNonce < targetNonce) {
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} aligning nonce from ${currentNonce} to ${targetNonce}`);
// Выравниваем nonce нулевыми транзакциями
for (let i = currentNonce; i < targetNonce; i++) {
try {
const fillerTx = await wallet.sendTransaction({
to: '0x000000000000000000000000000000000000dEaD',
value: 0,
gasLimit: 21000,
nonce: i,
...feeOverrides
});
await fillerTx.wait();
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx ${i} confirmed`);
// Обновляем nonce в кэше
nonceManager.reserveNonce(wallet.address, Number(net.chainId), i);
} catch (fillerError) {
logger.error(`[MODULES_DBG] chainId=${Number(net.chainId)} filler tx ${i} failed: ${fillerError.message}`);
throw fillerError;
}
}
}
// ВАЖНО: Обновляем targetNonce на актуальный nonce для следующей попытки
targetNonce = currentNonce;
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} updated targetNonce to: ${targetNonce}`);
// Короткая задержка перед следующей попыткой
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
// Если это не ошибка nonce или исчерпаны попытки, выбрасываем ошибку
if (deployAttempts >= maxDeployAttempts) {
throw new Error(`Module deployment failed after ${maxDeployAttempts} attempts: ${errorMsg}`);
}
// Для других ошибок делаем короткую задержку и пробуем снова
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
const rc = await tx.wait();
const deployedAddress = rc.contractAddress || predictedAddress;
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} ${moduleType} deployed at=${deployedAddress}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} ${moduleType} deployed at=${deployedAddress}`);
return { address: deployedAddress, chainId: Number(net.chainId) };
}
@@ -231,11 +306,16 @@ async function deployModuleInNetwork(rpcUrl, pk, salt, initCodeHash, targetNonce
// Деплой всех модулей в одной сети
async function deployAllModulesInNetwork(rpcUrl, pk, salt, dleAddress, modulesToDeploy, moduleInits, targetNonces) {
const { ethers } = hre;
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(pk, provider);
const net = await provider.getNetwork();
// Используем новый менеджер RPC с retry логикой
const { provider, wallet, network } = await createRPCConnection(rpcUrl, pk, {
maxRetries: 3,
timeout: 30000
});
const net = network;
console.log(`[MODULES_DBG] chainId=${Number(net.chainId)} deploying modules: ${modulesToDeploy.join(', ')}`);
logger.info(`[MODULES_DBG] chainId=${Number(net.chainId)} deploying modules: ${modulesToDeploy.join(', ')}`);
const results = {};
@@ -248,14 +328,14 @@ async function deployAllModulesInNetwork(rpcUrl, pk, salt, dleAddress, modulesTo
deploymentWebSocketService.addDeploymentLog(dleAddress, 'info', `Деплой модуля ${moduleType} в сети ${net.name || net.chainId}`);
if (!MODULE_CONFIGS[moduleType]) {
console.error(`[MODULES_DBG] chainId=${Number(net.chainId)} Unknown module type: ${moduleType}`);
logger.error(`[MODULES_DBG] chainId=${Number(net.chainId)} Unknown module type: ${moduleType}`);
results[moduleType] = { success: false, error: `Unknown module type: ${moduleType}` };
deploymentWebSocketService.addDeploymentLog(dleAddress, 'error', `Неизвестный тип модуля: ${moduleType}`);
continue;
}
if (!moduleInit) {
console.error(`[MODULES_DBG] chainId=${Number(net.chainId)} No init code for module: ${moduleType}`);
logger.error(`[MODULES_DBG] chainId=${Number(net.chainId)} No init code for module: ${moduleType}`);
results[moduleType] = { success: false, error: `No init code for module: ${moduleType}` };
deploymentWebSocketService.addDeploymentLog(dleAddress, 'error', `Отсутствует код инициализации для модуля: ${moduleType}`);
continue;
@@ -266,7 +346,7 @@ async function deployAllModulesInNetwork(rpcUrl, pk, salt, dleAddress, modulesTo
results[moduleType] = { ...result, success: true };
deploymentWebSocketService.addDeploymentLog(dleAddress, 'success', `Модуль ${moduleType} успешно задеплоен в сети ${net.name || net.chainId}: ${result.address}`);
} catch (error) {
console.error(`[MODULES_DBG] chainId=${Number(net.chainId)} ${moduleType} deployment failed:`, error.message);
logger.error(`[MODULES_DBG] chainId=${Number(net.chainId)} ${moduleType} deployment failed:`, error.message);
results[moduleType] = {
chainId: Number(net.chainId),
success: false,
@@ -287,9 +367,10 @@ async function deployAllModulesInNetwork(rpcUrl, pk, salt, dleAddress, modulesTo
async function deployAllModulesInAllNetworks(networks, pk, salt, dleAddress, modulesToDeploy, moduleInits, targetNonces) {
const results = [];
for (let i = 0; i < networks.length; i++) {
const rpcUrl = networks[i];
console.log(`[MODULES_DBG] deploying modules to network ${i + 1}/${networks.length}: ${rpcUrl}`);
for (let i = 0; i < connections.length; i++) {
const connection = connections[i];
const rpcUrl = connection.rpcUrl;
logger.info(`[MODULES_DBG] deploying modules to network ${i + 1}/${connections.length}: ${rpcUrl}`);
const result = await deployAllModulesInNetwork(rpcUrl, pk, salt, dleAddress, modulesToDeploy, moduleInits, targetNonces);
results.push(result);
@@ -323,10 +404,10 @@ async function main() {
// Проверяем, передан ли конкретный deploymentId
const deploymentId = process.env.DEPLOYMENT_ID;
if (deploymentId) {
console.log(`🔍 Ищем параметры для deploymentId: ${deploymentId}`);
logger.info(`🔍 Ищем параметры для deploymentId: ${deploymentId}`);
params = await deployParamsService.getDeployParams(deploymentId);
if (params) {
console.log('✅ Параметры загружены из базы данных по deploymentId');
logger.info('✅ Параметры загружены из базы данных по deploymentId');
} else {
throw new Error(`Параметры деплоя не найдены для deploymentId: ${deploymentId}`);
}
@@ -335,7 +416,7 @@ async function main() {
const latestParams = await deployParamsService.getLatestDeployParams(1);
if (latestParams.length > 0) {
params = latestParams[0];
console.log('✅ Параметры загружены из базы данных (последние)');
logger.info('✅ Параметры загружены из базы данных (последние)');
} else {
throw new Error('Параметры деплоя не найдены в базе данных');
}
@@ -343,18 +424,11 @@ async function main() {
await deployParamsService.close();
} catch (dbError) {
console.log('⚠️ Не удалось загрузить параметры из БД, пытаемся загрузить из файла:', dbError.message);
// Fallback к файлу
const paramsPath = path.join(__dirname, './current-params.json');
if (!fs.existsSync(paramsPath)) {
throw new Error('Файл параметров не найден: ' + paramsPath);
}
params = JSON.parse(fs.readFileSync(paramsPath, 'utf8'));
console.log('✅ Параметры загружены из файла');
logger.error('❌ Критическая ошибка: не удалось загрузить параметры из БД:', dbError.message);
logger.error('❌ Система должна использовать только базу данных для хранения параметров деплоя');
throw new Error(`Не удалось загрузить параметры деплоя из БД: ${dbError.message}. Система должна использовать только базу данных.`);
}
console.log('[MODULES_DBG] Загружены параметры:', {
logger.info('[MODULES_DBG] Загружены параметры:', {
name: params.name,
symbol: params.symbol,
supportedChainIds: params.supportedChainIds,
@@ -370,13 +444,13 @@ async function main() {
let modulesToDeploy;
if (moduleTypeFromArgs) {
modulesToDeploy = [moduleTypeFromArgs];
console.log(`[MODULES_DBG] Деплой конкретного модуля: ${moduleTypeFromArgs}`);
logger.info(`[MODULES_DBG] Деплой конкретного модуля: ${moduleTypeFromArgs}`);
} else if (params.modulesToDeploy && params.modulesToDeploy.length > 0) {
modulesToDeploy = params.modulesToDeploy;
console.log(`[MODULES_DBG] Деплой модулей из БД: ${modulesToDeploy.join(', ')}`);
logger.info(`[MODULES_DBG] Деплой модулей из БД: ${modulesToDeploy.join(', ')}`);
} else {
modulesToDeploy = ['treasury', 'timelock', 'reader'];
console.log(`[MODULES_DBG] Деплой модулей по умолчанию: ${modulesToDeploy.join(', ')}`);
logger.info(`[MODULES_DBG] Деплой модулей по умолчанию: ${modulesToDeploy.join(', ')}`);
}
if (!pk) throw new Error('PRIVATE_KEY not found in params or environment');
@@ -384,11 +458,11 @@ async function main() {
if (!salt) throw new Error('CREATE2_SALT not found in params');
if (networks.length === 0) throw new Error('RPC URLs not found in params');
console.log(`[MODULES_DBG] Starting modules deployment to ${networks.length} networks`);
console.log(`[MODULES_DBG] DLE Address: ${dleAddress}`);
console.log(`[MODULES_DBG] Modules to deploy: ${modulesToDeploy.join(', ')}`);
console.log(`[MODULES_DBG] Networks:`, networks);
console.log(`[MODULES_DBG] Using private key from: ${params.privateKey ? 'database' : 'environment'}`);
logger.info(`[MODULES_DBG] Starting modules deployment to ${networks.length} networks`);
logger.info(`[MODULES_DBG] DLE Address: ${dleAddress}`);
logger.info(`[MODULES_DBG] Modules to deploy: ${modulesToDeploy.join(', ')}`);
logger.info(`[MODULES_DBG] Networks:`, networks);
logger.info(`[MODULES_DBG] Using private key from: ${params.privateKey ? 'database' : 'environment'}`);
// Уведомляем WebSocket клиентов о начале деплоя
if (moduleTypeFromArgs) {
@@ -400,9 +474,11 @@ async function main() {
}
// Устанавливаем API ключ Etherscan из базы данных, если доступен
if (params.etherscanApiKey || params.etherscan_api_key) {
process.env.ETHERSCAN_API_KEY = params.etherscanApiKey || params.etherscan_api_key;
console.log(`[MODULES_DBG] Using Etherscan API key from database`);
const ApiKeyManager = require('../../utils/apiKeyManager');
const etherscanKey = ApiKeyManager.getAndSetEtherscanApiKey(params);
if (etherscanKey) {
logger.info(`[MODULES_DBG] Using Etherscan API key from database`);
}
// Проверяем, что все модули поддерживаются
@@ -420,28 +496,43 @@ async function main() {
const ContractFactory = await hre.ethers.getContractFactory(moduleConfig.contractName);
// Получаем аргументы конструктора для первой сети (для расчета init кода)
const firstProvider = new hre.ethers.JsonRpcProvider(networks[0]);
const firstWallet = new hre.ethers.Wallet(pk, firstProvider);
const firstNetwork = await firstProvider.getNetwork();
const firstConnection = await createRPCConnection(networks[0], pk, {
maxRetries: 3,
timeout: 30000
});
const firstProvider = firstConnection.provider;
const firstWallet = firstConnection.wallet;
const firstNetwork = firstConnection.network;
// Получаем аргументы конструктора
const constructorArgs = moduleConfig.constructorArgs(dleAddress, Number(firstNetwork.chainId), firstWallet.address);
console.log(`[MODULES_DBG] ${moduleType} constructor args:`, constructorArgs);
logger.info(`[MODULES_DBG] ${moduleType} constructor args:`, constructorArgs);
const deployTx = await ContractFactory.getDeployTransaction(...constructorArgs);
moduleInits[moduleType] = deployTx.data;
moduleInitCodeHashes[moduleType] = ethers.keccak256(deployTx.data);
console.log(`[MODULES_DBG] ${moduleType} init code prepared, hash: ${moduleInitCodeHashes[moduleType]}`);
logger.info(`[MODULES_DBG] ${moduleType} init code prepared, hash: ${moduleInitCodeHashes[moduleType]}`);
}
// Подготовим провайдеры и вычислим общие nonce для каждого модуля
const providers = networks.map(u => new hre.ethers.JsonRpcProvider(u));
const wallets = providers.map(p => new hre.ethers.Wallet(pk, p));
// Создаем RPC соединения с retry логикой
logger.info(`[MODULES_DBG] Создаем RPC соединения для ${networks.length} сетей...`);
const connections = await createMultipleRPCConnections(networks, pk, {
maxRetries: 3,
timeout: 30000
});
if (connections.length === 0) {
throw new Error('Не удалось установить ни одного RPC соединения');
}
logger.info(`[MODULES_DBG] ✅ Успешно подключились к ${connections.length}/${networks.length} сетям`);
const nonces = [];
for (let i = 0; i < providers.length; i++) {
const n = await providers[i].getTransactionCount(wallets[i].address, 'pending');
for (const connection of connections) {
const n = await nonceManager.getNonce(connection.wallet.address, connection.rpcUrl, connection.chainId);
nonces.push(n);
}
@@ -454,48 +545,50 @@ async function main() {
currentMaxNonce++; // каждый следующий модуль получает nonce +1
}
console.log(`[MODULES_DBG] nonces=${JSON.stringify(nonces)} targetNonces=${JSON.stringify(targetNonces)}`);
logger.info(`[MODULES_DBG] nonces=${JSON.stringify(nonces)} targetNonces=${JSON.stringify(targetNonces)}`);
// ПАРАЛЛЕЛЬНЫЙ деплой всех модулей во всех сетях одновременно
console.log(`[MODULES_DBG] Starting PARALLEL deployment of all modules to ${networks.length} networks`);
logger.info(`[MODULES_DBG] Starting PARALLEL deployment of all modules to ${networks.length} networks`);
const deploymentPromises = networks.map(async (rpcUrl, networkIndex) => {
console.log(`[MODULES_DBG] 🚀 Starting deployment to network ${networkIndex + 1}/${networks.length}: ${rpcUrl}`);
logger.info(`[MODULES_DBG] 🚀 Starting deployment to network ${networkIndex + 1}/${networks.length}: ${rpcUrl}`);
try {
// Получаем chainId динамически из сети
const provider = new hre.ethers.JsonRpcProvider(rpcUrl);
const network = await provider.getNetwork();
// Получаем chainId динамически из сети с retry логикой
const { provider, network } = await createRPCConnection(rpcUrl, pk, {
maxRetries: 3,
timeout: 30000
});
const chainId = Number(network.chainId);
console.log(`[MODULES_DBG] 📡 Network ${networkIndex + 1} chainId: ${chainId}`);
logger.info(`[MODULES_DBG] 📡 Network ${networkIndex + 1} chainId: ${chainId}`);
const result = await deployAllModulesInNetwork(rpcUrl, pk, salt, dleAddress, modulesToDeploy, moduleInits, targetNonces);
console.log(`[MODULES_DBG] ✅ Network ${networkIndex + 1} (chainId: ${chainId}) deployment SUCCESS`);
logger.info(`[MODULES_DBG] ✅ Network ${networkIndex + 1} (chainId: ${chainId}) deployment SUCCESS`);
return { rpcUrl, chainId, ...result };
} catch (error) {
console.error(`[MODULES_DBG] ❌ Network ${networkIndex + 1} deployment FAILED:`, error.message);
logger.error(`[MODULES_DBG] ❌ Network ${networkIndex + 1} deployment FAILED:`, error.message);
return { rpcUrl, error: error.message };
}
});
// Ждем завершения всех деплоев
const deployResults = await Promise.all(deploymentPromises);
console.log(`[MODULES_DBG] All ${networks.length} deployments completed`);
logger.info(`[MODULES_DBG] All ${networks.length} deployments completed`);
// Логируем результаты деплоя для каждой сети
deployResults.forEach((result, index) => {
if (result.modules) {
console.log(`[MODULES_DBG] ✅ Network ${index + 1} (chainId: ${result.chainId}) SUCCESS`);
logger.info(`[MODULES_DBG] ✅ Network ${index + 1} (chainId: ${result.chainId}) SUCCESS`);
Object.entries(result.modules).forEach(([moduleType, moduleResult]) => {
if (moduleResult.success) {
console.log(`[MODULES_DBG] ✅ ${moduleType}: ${moduleResult.address}`);
logger.info(`[MODULES_DBG] ✅ ${moduleType}: ${moduleResult.address}`);
} else {
console.log(`[MODULES_DBG] ❌ ${moduleType}: ${moduleResult.error}`);
logger.info(`[MODULES_DBG] ❌ ${moduleType}: ${moduleResult.error}`);
}
});
} else {
console.log(`[MODULES_DBG] ❌ Network ${index + 1} (chainId: ${result.chainId}) FAILED: ${result.error}`);
logger.info(`[MODULES_DBG] ❌ Network ${index + 1} (chainId: ${result.chainId}) FAILED: ${result.error}`);
}
});
@@ -506,38 +599,38 @@ async function main() {
.map(r => r.modules[moduleType].address);
const uniqueAddresses = [...new Set(addresses)];
console.log(`[MODULES_DBG] ${moduleType} addresses:`, addresses);
console.log(`[MODULES_DBG] ${moduleType} unique addresses:`, uniqueAddresses);
logger.info(`[MODULES_DBG] ${moduleType} addresses:`, addresses);
logger.info(`[MODULES_DBG] ${moduleType} unique addresses:`, uniqueAddresses);
if (uniqueAddresses.length > 1) {
console.error(`[MODULES_DBG] ERROR: ${moduleType} addresses are different across networks!`);
console.error(`[MODULES_DBG] addresses:`, uniqueAddresses);
logger.error(`[MODULES_DBG] ERROR: ${moduleType} addresses are different across networks!`);
logger.error(`[MODULES_DBG] addresses:`, uniqueAddresses);
throw new Error(`Nonce alignment failed for ${moduleType} - addresses are different`);
}
if (uniqueAddresses.length === 0) {
console.error(`[MODULES_DBG] ERROR: No successful ${moduleType} deployments!`);
logger.error(`[MODULES_DBG] ERROR: No successful ${moduleType} deployments!`);
throw new Error(`No successful ${moduleType} deployments`);
}
console.log(`[MODULES_DBG] SUCCESS: All ${moduleType} addresses are identical:`, uniqueAddresses[0]);
logger.info(`[MODULES_DBG] SUCCESS: All ${moduleType} addresses are identical:`, uniqueAddresses[0]);
}
// Верификация во всех сетях через отдельный скрипт
console.log(`[MODULES_DBG] Starting verification in all networks...`);
logger.info(`[MODULES_DBG] Starting verification in all networks...`);
deploymentWebSocketService.addDeploymentLog(dleAddress, 'info', 'Начало верификации модулей во всех сетях...');
// Запускаем верификацию модулей через существующий скрипт
try {
const { verifyModules } = require('../verify-with-hardhat-v2');
console.log(`[MODULES_DBG] Запускаем верификацию модулей...`);
logger.info(`[MODULES_DBG] Запускаем верификацию модулей...`);
deploymentWebSocketService.addDeploymentLog(dleAddress, 'info', 'Верификация контрактов в блокчейн-сканерах...');
await verifyModules();
console.log(`[MODULES_DBG] Верификация модулей завершена`);
logger.info(`[MODULES_DBG] Верификация модулей завершена`);
deploymentWebSocketService.addDeploymentLog(dleAddress, 'success', 'Верификация модулей завершена успешно');
} catch (verifyError) {
console.log(`[MODULES_DBG] Ошибка при верификации модулей: ${verifyError.message}`);
logger.info(`[MODULES_DBG] Ошибка при верификации модулей: ${verifyError.message}`);
deploymentWebSocketService.addDeploymentLog(dleAddress, 'error', `Ошибка при верификации модулей: ${verifyError.message}`);
}
@@ -562,7 +655,7 @@ async function main() {
}, {}) : {}
}));
console.log('MODULES_DEPLOY_RESULT', JSON.stringify(finalResults));
logger.info('MODULES_DEPLOY_RESULT', JSON.stringify(finalResults));
// Сохраняем результаты в отдельные файлы для каждого модуля
const dleDir = path.join(__dirname, '../contracts-data/modules');
@@ -602,8 +695,10 @@ async function main() {
const verification = verificationResult?.modules?.[moduleType] || 'unknown';
try {
const provider = new hre.ethers.JsonRpcProvider(rpcUrl);
const network = await provider.getNetwork();
const { provider, network } = await createRPCConnection(rpcUrl, pk, {
maxRetries: 3,
timeout: 30000
});
moduleInfo.networks.push({
chainId: Number(network.chainId),
@@ -614,7 +709,7 @@ async function main() {
error: moduleResult?.error || null
});
} catch (error) {
console.error(`[MODULES_DBG] Ошибка получения chainId для модуля ${moduleType} в сети ${i + 1}:`, error.message);
logger.error(`[MODULES_DBG] Ошибка получения chainId для модуля ${moduleType} в сети ${i + 1}:`, error.message);
moduleInfo.networks.push({
chainId: null,
rpcUrl: rpcUrl,
@@ -630,15 +725,15 @@ async function main() {
const fileName = `${moduleType}-${dleAddress.toLowerCase()}.json`;
const filePath = path.join(dleDir, fileName);
fs.writeFileSync(filePath, JSON.stringify(moduleInfo, null, 2));
console.log(`[MODULES_DBG] ${moduleType} info saved to: ${filePath}`);
logger.info(`[MODULES_DBG] ${moduleType} info saved to: ${filePath}`);
}
console.log('[MODULES_DBG] All modules deployment completed!');
console.log(`[MODULES_DBG] Available modules: ${Object.keys(MODULE_CONFIGS).join(', ')}`);
console.log(`[MODULES_DBG] DLE Address: ${dleAddress}`);
console.log(`[MODULES_DBG] DLE Name: ${params.name}`);
console.log(`[MODULES_DBG] DLE Symbol: ${params.symbol}`);
console.log(`[MODULES_DBG] DLE Location: ${params.location}`);
logger.info('[MODULES_DBG] All modules deployment completed!');
logger.info(`[MODULES_DBG] Available modules: ${Object.keys(MODULE_CONFIGS).join(', ')}`);
logger.info(`[MODULES_DBG] DLE Address: ${dleAddress}`);
logger.info(`[MODULES_DBG] DLE Name: ${params.name}`);
logger.info(`[MODULES_DBG] DLE Symbol: ${params.symbol}`);
logger.info(`[MODULES_DBG] DLE Location: ${params.location}`);
// Создаем сводный отчет о деплое
const summaryReport = {
@@ -675,10 +770,10 @@ async function main() {
// Сохраняем сводный отчет
const summaryPath = path.join(__dirname, '../contracts-data/modules-deploy-summary.json');
fs.writeFileSync(summaryPath, JSON.stringify(summaryReport, null, 2));
console.log(`[MODULES_DBG] Сводный отчет сохранен: ${summaryPath}`);
logger.info(`[MODULES_DBG] Сводный отчет сохранен: ${summaryPath}`);
// Уведомляем WebSocket клиентов о завершении деплоя
console.log(`[MODULES_DBG] finalResults:`, JSON.stringify(finalResults, null, 2));
logger.info(`[MODULES_DBG] finalResults:`, JSON.stringify(finalResults, null, 2));
const successfulModules = finalResults.reduce((acc, result) => {
if (result.modules) {
@@ -694,14 +789,14 @@ async function main() {
const successCount = Object.keys(successfulModules).length;
const totalCount = modulesToDeploy.length;
console.log(`[MODULES_DBG] successfulModules:`, successfulModules);
console.log(`[MODULES_DBG] successCount: ${successCount}, totalCount: ${totalCount}`);
logger.info(`[MODULES_DBG] successfulModules:`, successfulModules);
logger.info(`[MODULES_DBG] successCount: ${successCount}, totalCount: ${totalCount}`);
if (successCount === totalCount) {
console.log(`[MODULES_DBG] Вызываем finishDeploymentSession с success=true`);
logger.info(`[MODULES_DBG] Вызываем finishDeploymentSession с success=true`);
deploymentWebSocketService.finishDeploymentSession(dleAddress, true, `Деплой завершен успешно! Задеплоено ${successCount} из ${totalCount} модулей`);
} else {
console.log(`[MODULES_DBG] Вызываем finishDeploymentSession с success=false`);
logger.info(`[MODULES_DBG] Вызываем finishDeploymentSession с success=false`);
deploymentWebSocketService.finishDeploymentSession(dleAddress, false, `Деплой завершен с ошибками. Задеплоено ${successCount} из ${totalCount} модулей`);
}
@@ -709,4 +804,4 @@ async function main() {
deploymentWebSocketService.notifyModulesUpdated(dleAddress);
}
main().catch((e) => { console.error(e); process.exit(1); });
main().catch((e) => { logger.error(e); process.exit(1); });

View File

@@ -11,64 +11,108 @@
*/
/* eslint-disable no-console */
// КРИТИЧЕСКИЙ ЛОГ - СКРИПТ ЗАПУЩЕН!
console.log('[MULTI_DBG] 🚀 СКРИПТ DEPLOY-MULTICHAIN.JS ЗАПУЩЕН!');
console.log('[MULTI_DBG] 📦 Импортируем hardhat...');
const hre = require('hardhat');
console.log('[MULTI_DBG] ✅ hardhat импортирован');
console.log('[MULTI_DBG] 📦 Импортируем path...');
const path = require('path');
console.log('[MULTI_DBG] ✅ path импортирован');
console.log('[MULTI_DBG] 📦 Импортируем fs...');
const fs = require('fs');
console.log('[MULTI_DBG] ✅ fs импортирован');
console.log('[MULTI_DBG] 📦 Импортируем rpcProviderService...');
const { getRpcUrlByChainId } = require('../../services/rpcProviderService');
console.log('[MULTI_DBG] ✅ rpcProviderService импортирован');
// Подбираем безопасные gas/fee для разных сетей (включая L2)
async function getFeeOverrides(provider, { minPriorityGwei = 1n, minFeeGwei = 20n } = {}) {
const fee = await provider.getFeeData();
const overrides = {};
const minPriority = (await (async () => hre.ethers.parseUnits(minPriorityGwei.toString(), 'gwei'))());
const minFee = (await (async () => hre.ethers.parseUnits(minFeeGwei.toString(), 'gwei'))());
if (fee.maxFeePerGas) {
overrides.maxFeePerGas = fee.maxFeePerGas < minFee ? minFee : fee.maxFeePerGas;
overrides.maxPriorityFeePerGas = (fee.maxPriorityFeePerGas && fee.maxPriorityFeePerGas > 0n)
? fee.maxPriorityFeePerGas
: minPriority;
} else if (fee.gasPrice) {
overrides.gasPrice = fee.gasPrice < minFee ? minFee : fee.gasPrice;
}
return overrides;
}
console.log('[MULTI_DBG] 📦 Импортируем logger...');
const logger = require('../../utils/logger');
console.log('[MULTI_DBG] ✅ logger импортирован');
async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, dleInit, params) {
console.log('[MULTI_DBG] 📦 Импортируем deploymentUtils...');
const { getFeeOverrides, createProviderAndWallet, alignNonce, getNetworkInfo, createMultipleRPCConnections, sendTransactionWithRetry, createRPCConnection } = require('../../utils/deploymentUtils');
console.log('[MULTI_DBG] ✅ deploymentUtils импортирован');
console.log('[MULTI_DBG] 📦 Импортируем nonceManager...');
const { nonceManager } = require('../../utils/nonceManager');
console.log('[MULTI_DBG] ✅ nonceManager импортирован');
console.log('[MULTI_DBG] 🎯 ВСЕ ИМПОРТЫ УСПЕШНЫ!');
console.log('[MULTI_DBG] 🔍 ПРОВЕРЯЕМ ФУНКЦИИ...');
console.log('[MULTI_DBG] deployInNetwork:', typeof deployInNetwork);
console.log('[MULTI_DBG] main:', typeof main);
async function deployInNetwork(rpcUrl, pk, initCodeHash, targetDLENonce, dleInit, params) {
const { ethers } = hre;
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(pk, provider);
const net = await provider.getNetwork();
// Используем новый менеджер RPC с retry логикой
const { provider, wallet, network } = await createRPCConnection(rpcUrl, pk, {
maxRetries: 3,
timeout: 30000
});
const net = network;
// DEBUG: базовая информация по сети
try {
const calcInitHash = ethers.keccak256(dleInit);
const saltLen = ethers.getBytes(salt).length;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} rpc=${rpcUrl}`);
console.log(`[MULTI_DBG] wallet=${wallet.address} targetDLENonce=${targetDLENonce}`);
console.log(`[MULTI_DBG] saltLenBytes=${saltLen} salt=${salt}`);
console.log(`[MULTI_DBG] initCodeHash(provided)=${initCodeHash}`);
console.log(`[MULTI_DBG] initCodeHash(calculated)=${calcInitHash}`);
console.log(`[MULTI_DBG] dleInit.lenBytes=${ethers.getBytes(dleInit).length} head16=${dleInit.slice(0, 34)}...`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} rpc=${rpcUrl}`);
logger.info(`[MULTI_DBG] wallet=${wallet.address} targetDLENonce=${targetDLENonce}`);
logger.info(`[MULTI_DBG] initCodeHash(provided)=${initCodeHash}`);
logger.info(`[MULTI_DBG] initCodeHash(calculated)=${calcInitHash}`);
logger.info(`[MULTI_DBG] dleInit.lenBytes=${ethers.getBytes(dleInit).length} head16=${dleInit.slice(0, 34)}...`);
} catch (e) {
console.log('[MULTI_DBG] precheck error', e?.message || e);
logger.error('[MULTI_DBG] precheck error', e?.message || e);
}
// 1) Выравнивание nonce до targetDLENonce нулевыми транзакциями (если нужно)
let current = await provider.getTransactionCount(wallet.address, 'pending');
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} current nonce=${current} target=${targetDLENonce}`);
// 1) Используем NonceManager для правильного управления nonce
const chainId = Number(net.chainId);
let current = await nonceManager.getNonce(wallet.address, rpcUrl, chainId);
logger.info(`[MULTI_DBG] chainId=${chainId} current nonce=${current} target=${targetDLENonce}`);
if (current > targetDLENonce) {
throw new Error(`Current nonce ${current} > targetDLENonce ${targetDLENonce} on chainId=${Number(net.chainId)}`);
logger.warn(`[MULTI_DBG] chainId=${Number(net.chainId)} current nonce ${current} > targetDLENonce ${targetDLENonce} - waiting for sync`);
// Ждем синхронизации nonce (максимум 60 секунд с прогрессивной задержкой)
let waitTime = 0;
let checkInterval = 1000; // Начинаем с 1 секунды
while (current > targetDLENonce && waitTime < 60000) {
await new Promise(resolve => setTimeout(resolve, checkInterval));
current = await nonceManager.getNonce(wallet.address, rpcUrl, chainId);
waitTime += checkInterval;
// Прогрессивно увеличиваем интервал проверки
if (waitTime > 10000) checkInterval = 2000;
if (waitTime > 30000) checkInterval = 5000;
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} waiting for nonce sync: ${current} > ${targetDLENonce} (${waitTime}ms, next check in ${checkInterval}ms)`);
}
if (current > targetDLENonce) {
const errorMsg = `Nonce sync timeout: current ${current} > targetDLENonce ${targetDLENonce} on chainId=${Number(net.chainId)}. This may indicate network issues or the wallet was used for other transactions.`;
logger.error(`[MULTI_DBG] ${errorMsg}`);
throw new Error(errorMsg);
}
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce sync completed: ${current} <= ${targetDLENonce}`);
}
if (current < targetDLENonce) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} starting nonce alignment: ${current} -> ${targetDLENonce} (${targetDLENonce - current} transactions needed)`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} starting nonce alignment: ${current} -> ${targetDLENonce} (${targetDLENonce - current} transactions needed)`);
} else {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce already aligned: ${current} = ${targetDLENonce}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce already aligned: ${current} = ${targetDLENonce}`);
}
if (current < targetDLENonce) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} aligning nonce from ${current} to ${targetDLENonce} (${targetDLENonce - current} transactions needed)`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} aligning nonce from ${current} to ${targetDLENonce} (${targetDLENonce - current} transactions needed)`);
// Используем burn address для более надежных транзакций
const burnAddress = "0x000000000000000000000000000000000000dEaD";
@@ -79,7 +123,7 @@ async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, d
let sent = false;
let lastErr = null;
for (let attempt = 0; attempt < 3 && !sent; attempt++) {
for (let attempt = 0; attempt < 5 && !sent; attempt++) {
try {
const txReq = {
to: burnAddress, // отправляем на burn address вместо своего адреса
@@ -88,49 +132,87 @@ async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, d
gasLimit,
...overrides
};
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} sending filler tx nonce=${current} attempt=${attempt + 1}`);
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} tx details: to=${burnAddress}, value=0, gasLimit=${gasLimit}`);
const txFill = await wallet.sendTransaction(txReq);
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx sent, hash=${txFill.hash}, waiting for confirmation...`);
await txFill.wait();
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} confirmed, hash=${txFill.hash}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} sending filler tx nonce=${current} attempt=${attempt + 1}/5`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} tx details: to=${burnAddress}, value=0, gasLimit=${gasLimit}`);
const { tx: txFill, receipt } = await sendTransactionWithRetry(wallet, txReq, { maxRetries: 3 });
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx sent, hash=${txFill.hash}, waiting for confirmation...`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} confirmed, hash=${txFill.hash}`);
sent = true;
} catch (e) {
lastErr = e;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} attempt=${attempt + 1} failed: ${e?.message || e}`);
const errorMsg = e?.message || e;
logger.warn(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} attempt=${attempt + 1} failed: ${errorMsg}`);
if (String(e?.message || '').toLowerCase().includes('intrinsic gas too low') && attempt < 2) {
gasLimit = 50000; // увеличиваем gas limit
// Обработка специфических ошибок
if (String(errorMsg).toLowerCase().includes('intrinsic gas too low') && attempt < 4) {
gasLimit = Math.min(gasLimit * 2, 100000); // увеличиваем gas limit с ограничением
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} increased gas limit to ${gasLimit}`);
continue;
}
if (String(e?.message || '').toLowerCase().includes('nonce too low') && attempt < 2) {
// Обновляем nonce и пробуем снова
current = await provider.getTransactionCount(wallet.address, 'pending');
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} updated nonce to ${current}`);
if (String(errorMsg).toLowerCase().includes('nonce too low') && attempt < 4) {
// Сбрасываем кэш nonce и получаем актуальный
nonceManager.resetNonce(wallet.address, chainId);
const newNonce = await nonceManager.getNonce(wallet.address, rpcUrl, chainId, { timeout: 15000, maxRetries: 5 });
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce changed from ${current} to ${newNonce}`);
current = newNonce;
// Если новый nonce больше целевого, обновляем targetDLENonce
if (current > targetDLENonce) {
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} current nonce ${current} > target nonce ${targetDLENonce}, updating target`);
targetDLENonce = current;
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} updated targetDLENonce to: ${targetDLENonce}`);
}
continue;
}
throw e;
if (String(errorMsg).toLowerCase().includes('insufficient funds') && attempt < 4) {
logger.error(`[MULTI_DBG] chainId=${Number(net.chainId)} insufficient funds for nonce alignment`);
throw new Error(`Insufficient funds for nonce alignment on chainId=${Number(net.chainId)}. Please add more ETH to the wallet.`);
}
if (String(errorMsg).toLowerCase().includes('network') && attempt < 4) {
logger.warn(`[MULTI_DBG] chainId=${Number(net.chainId)} network error, retrying in ${(attempt + 1) * 2} seconds...`);
await new Promise(resolve => setTimeout(resolve, (attempt + 1) * 2000));
continue;
}
// Если это последняя попытка, выбрасываем ошибку
if (attempt === 4) {
throw new Error(`Failed to send filler transaction after 5 attempts: ${errorMsg}`);
}
}
}
if (!sent) {
console.error(`[MULTI_DBG] chainId=${Number(net.chainId)} failed to send filler tx for nonce=${current}`);
logger.error(`[MULTI_DBG] chainId=${Number(net.chainId)} failed to send filler tx for nonce=${current}`);
throw lastErr || new Error('filler tx failed');
}
current++;
}
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce alignment completed, current nonce=${current}`);
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} ready for DLE deployment with nonce=${current}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce alignment completed, current nonce=${current}`);
// Зарезервируем nonce в NonceManager
nonceManager.reserveNonce(wallet.address, chainId, targetDLENonce);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} ready for DLE deployment with nonce=${current}`);
} else {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce already aligned at ${current}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce already aligned at ${current}`);
}
// 2) Деплой DLE напрямую на согласованном nonce
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} deploying DLE directly with nonce=${targetDLENonce}`);
// 2) Проверяем баланс перед деплоем
const balance = await provider.getBalance(wallet.address, 'latest');
const balanceEth = ethers.formatEther(balance);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} wallet balance: ${balanceEth} ETH`);
if (balance < ethers.parseEther('0.01')) {
throw new Error(`Insufficient balance for deployment on chainId=${Number(net.chainId)}. Current: ${balanceEth} ETH, required: 0.01 ETH minimum`);
}
// 3) Деплой DLE с актуальным nonce
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} deploying DLE with current nonce`);
const feeOverrides = await getFeeOverrides(provider);
let gasLimit;
@@ -147,90 +229,137 @@ async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, d
const fallbackGas = maxByBalance > 5_000_000n ? 5_000_000n : (maxByBalance < 2_500_000n ? 2_500_000n : maxByBalance);
gasLimit = est ? (est + est / 5n) : fallbackGas;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} estGas=${est?.toString?.()||'null'} effGasPrice=${effPrice?.toString?.()||'0'} maxByBalance=${maxByBalance.toString()} chosenGasLimit=${gasLimit.toString()}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} estGas=${est?.toString?.()||'null'} effGasPrice=${effPrice?.toString?.()||'0'} maxByBalance=${maxByBalance.toString()} chosenGasLimit=${gasLimit.toString()}`);
} catch (_) {
gasLimit = 3_000_000n;
}
// Вычисляем предсказанный адрес DLE
const predictedAddress = ethers.getCreateAddress({
// Вычисляем предсказанный адрес DLE с целевым nonce (детерминированный деплой)
let predictedAddress = ethers.getCreateAddress({
from: wallet.address,
nonce: targetDLENonce
});
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} predicted DLE address=${predictedAddress}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} predicted DLE address=${predictedAddress} (nonce=${targetDLENonce})`);
// Проверяем, не развернут ли уже контракт
const existingCode = await provider.getCode(predictedAddress);
if (existingCode && existingCode !== '0x') {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} DLE already exists at predictedAddress, skip deploy`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} DLE already exists at predictedAddress, skip deploy`);
// Проверяем и инициализируем логотип для существующего контракта
if (params.logoURI && params.logoURI !== '') {
try {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} checking logoURI for existing contract`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} checking logoURI for existing contract`);
const DLE = await hre.ethers.getContractFactory('DLE');
const dleContract = DLE.attach(predictedAddress);
const currentLogo = await dleContract.logoURI();
if (currentLogo === '' || currentLogo === '0x') {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} initializing logoURI for existing contract: ${params.logoURI}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} initializing logoURI for existing contract: ${params.logoURI}`);
const logoTx = await dleContract.connect(wallet).initializeLogoURI(params.logoURI, feeOverrides);
await logoTx.wait();
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialized for existing contract`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialized for existing contract`);
} else {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI already set: ${currentLogo}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI already set: ${currentLogo}`);
}
} catch (error) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialization failed for existing contract: ${error.message}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialization failed for existing contract: ${error.message}`);
}
}
return { address: predictedAddress, chainId: Number(net.chainId) };
}
// Деплоим DLE
// Деплоим DLE с retry логикой для обработки race conditions
let tx;
try {
tx = await wallet.sendTransaction({
data: dleInit,
nonce: targetDLENonce,
gasLimit,
...feeOverrides
});
} catch (e) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} deploy error(first): ${e?.message || e}`);
// Повторная попытка с обновленным nonce
const updatedNonce = await provider.getTransactionCount(wallet.address, 'pending');
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} retry deploy with nonce=${updatedNonce}`);
tx = await wallet.sendTransaction({
data: dleInit,
nonce: updatedNonce,
gasLimit,
...feeOverrides
});
let deployAttempts = 0;
const maxDeployAttempts = 5;
while (deployAttempts < maxDeployAttempts) {
try {
deployAttempts++;
// Получаем актуальный nonce прямо перед отправкой транзакции
const currentNonce = await nonceManager.getNonce(wallet.address, rpcUrl, chainId, { timeout: 15000, maxRetries: 5 });
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} deploy attempt ${deployAttempts}/${maxDeployAttempts} with current nonce=${currentNonce} (target was ${targetDLENonce})`);
const txData = {
data: dleInit,
nonce: currentNonce,
gasLimit,
...feeOverrides
};
const result = await sendTransactionWithRetry(wallet, txData, { maxRetries: 3 });
tx = result.tx;
// Отмечаем транзакцию как pending в NonceManager
nonceManager.markTransactionPending(wallet.address, chainId, currentNonce, tx.hash);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} deploy successful on attempt ${deployAttempts}`);
break; // Успешно отправили, выходим из цикла
} catch (e) {
const errorMsg = e?.message || e;
logger.warn(`[MULTI_DBG] chainId=${Number(net.chainId)} deploy attempt ${deployAttempts} failed: ${errorMsg}`);
// Проверяем, является ли это ошибкой nonce
if (String(errorMsg).toLowerCase().includes('nonce too low') && deployAttempts < maxDeployAttempts) {
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce race condition detected, retrying...`);
// Получаем актуальный nonce из сети
const currentNonce = await nonceManager.getNonce(wallet.address, rpcUrl, chainId, { timeout: 15000, maxRetries: 5 });
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} current nonce: ${currentNonce}, target was: ${targetDLENonce}`);
// Обновляем targetDLENonce на актуальный nonce
targetDLENonce = currentNonce;
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} updated targetDLENonce to: ${targetDLENonce}`);
// Короткая задержка перед следующей попыткой
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
// Если это не ошибка nonce или исчерпаны попытки, выбрасываем ошибку
if (deployAttempts >= maxDeployAttempts) {
throw new Error(`Deployment failed after ${maxDeployAttempts} attempts: ${errorMsg}`);
}
// Для других ошибок делаем короткую задержку и пробуем снова
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
const rc = await tx.wait();
// Отмечаем транзакцию как подтвержденную в NonceManager
nonceManager.markTransactionConfirmed(wallet.address, chainId, tx.hash);
const deployedAddress = rc.contractAddress || predictedAddress;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} DLE deployed at=${deployedAddress}`);
// Проверяем, что адрес соответствует предсказанному
if (deployedAddress !== predictedAddress) {
logger.error(`[MULTI_DBG] chainId=${Number(net.chainId)} ADDRESS MISMATCH! predicted=${predictedAddress} actual=${deployedAddress}`);
throw new Error(`Address mismatch: predicted ${predictedAddress} != actual ${deployedAddress}`);
}
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} DLE deployed at=${deployedAddress}`);
// Инициализация логотипа если он указан
if (params.logoURI && params.logoURI !== '') {
try {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} initializing logoURI: ${params.logoURI}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} initializing logoURI: ${params.logoURI}`);
const DLE = await hre.ethers.getContractFactory('DLE');
const dleContract = DLE.attach(deployedAddress);
const logoTx = await dleContract.connect(wallet).initializeLogoURI(params.logoURI, feeOverrides);
await logoTx.wait();
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialized successfully`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialized successfully`);
} catch (error) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialization failed: ${error.message}`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} logoURI initialization failed: ${error.message}`);
// Не прерываем деплой из-за ошибки логотипа
}
} else {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} no logoURI specified, skipping initialization`);
logger.info(`[MULTI_DBG] chainId=${Number(net.chainId)} no logoURI specified, skipping initialization`);
}
return { address: deployedAddress, chainId: Number(net.chainId) };
@@ -238,9 +367,34 @@ async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, d
async function main() {
console.log('[MULTI_DBG] 🚀 ВХОДИМ В ФУНКЦИЮ MAIN!');
const { ethers } = hre;
console.log('[MULTI_DBG] ✅ ethers получен');
logger.info('[MULTI_DBG] 🚀 НАЧИНАЕМ ДЕПЛОЙ DLE КОНТРАКТА');
console.log('[MULTI_DBG] ✅ logger.info выполнен');
// Автоматически генерируем ABI и flattened контракт перед деплоем
logger.info('🔨 Генерация ABI файла...');
try {
const { generateABIFile } = require('../generate-abi');
generateABIFile();
logger.info('✅ ABI файл обновлен перед деплоем');
} catch (abiError) {
logger.warn('⚠️ Ошибка генерации ABI:', abiError.message);
}
logger.info('🔨 Генерация flattened контракта...');
try {
const { generateFlattened } = require('../generate-flattened');
await generateFlattened();
logger.info('✅ Flattened контракт обновлен перед деплоем');
} catch (flattenError) {
logger.warn('⚠️ Ошибка генерации flattened контракта:', flattenError.message);
}
// Загружаем параметры из базы данных или файла
console.log('[MULTI_DBG] 🔍 НАЧИНАЕМ ЗАГРУЗКУ ПАРАМЕТРОВ...');
let params;
try {
@@ -251,10 +405,10 @@ async function main() {
// Проверяем, передан ли конкретный deploymentId
const deploymentId = process.env.DEPLOYMENT_ID;
if (deploymentId) {
console.log(`🔍 Ищем параметры для deploymentId: ${deploymentId}`);
logger.info(`🔍 Ищем параметры для deploymentId: ${deploymentId}`);
params = await deployParamsService.getDeployParams(deploymentId);
if (params) {
console.log('✅ Параметры загружены из базы данных по deploymentId');
logger.info('✅ Параметры загружены из базы данных по deploymentId');
} else {
throw new Error(`Параметры деплоя не найдены для deploymentId: ${deploymentId}`);
}
@@ -263,7 +417,7 @@ async function main() {
const latestParams = await deployParamsService.getLatestDeployParams(1);
if (latestParams.length > 0) {
params = latestParams[0];
console.log('✅ Параметры загружены из базы данных (последние)');
logger.info('✅ Параметры загружены из базы данных (последние)');
} else {
throw new Error('Параметры деплоя не найдены в базе данных');
}
@@ -271,179 +425,197 @@ async function main() {
await deployParamsService.close();
} catch (dbError) {
console.log('⚠️ Не удалось загрузить параметры из БД, пытаемся загрузить из файла:', dbError.message);
// Fallback к файлу
const paramsPath = path.join(__dirname, './current-params.json');
if (!fs.existsSync(paramsPath)) {
throw new Error('Файл параметров не найден: ' + paramsPath);
logger.error('❌ Критическая ошибка: не удалось загрузить параметры из БД:', dbError.message);
throw new Error(`Деплой невозможен без параметров из БД: ${dbError.message}`);
}
params = JSON.parse(fs.readFileSync(paramsPath, 'utf8'));
console.log('✅ Параметры загружены из файла');
}
console.log('[MULTI_DBG] Загружены параметры:', {
logger.info('[MULTI_DBG] Загружены параметры:', {
name: params.name,
symbol: params.symbol,
supportedChainIds: params.supportedChainIds,
CREATE2_SALT: params.CREATE2_SALT
rpcUrls: params.rpcUrls || params.rpc_urls,
etherscanApiKey: params.etherscanApiKey || params.etherscan_api_key
});
const pk = params.private_key || process.env.PRIVATE_KEY;
const salt = params.CREATE2_SALT || params.create2_salt;
const networks = params.rpcUrls || params.rpc_urls || [];
// Устанавливаем API ключи Etherscan для верификации
const ApiKeyManager = require('../../utils/apiKeyManager');
const etherscanKey = ApiKeyManager.getAndSetEtherscanApiKey(params);
if (!etherscanKey) {
logger.warn('[MULTI_DBG] ⚠️ Etherscan API ключ не найден - верификация будет пропущена');
logger.warn(`[MULTI_DBG] Доступные поля: ${Object.keys(params).join(', ')}`);
}
if (!pk) throw new Error('Env: PRIVATE_KEY');
if (!salt) throw new Error('CREATE2_SALT not found in params');
if (networks.length === 0) throw new Error('RPC URLs not found in params');
// Prepare init code once
const DLE = await hre.ethers.getContractFactory('contracts/DLE.sol:DLE');
const dleConfig = {
name: params.name || '',
symbol: params.symbol || '',
location: params.location || '',
coordinates: params.coordinates || '',
jurisdiction: params.jurisdiction || 0,
oktmo: params.oktmo || '',
okvedCodes: params.okvedCodes || [],
kpp: params.kpp ? BigInt(params.kpp) : 0n,
quorumPercentage: params.quorumPercentage || 51,
initialPartners: params.initialPartners || [],
initialAmounts: (params.initialAmounts || []).map(amount => BigInt(amount) * BigInt(10**18)),
supportedChainIds: (params.supportedChainIds || []).map(id => BigInt(id))
};
const deployTx = await DLE.getDeployTransaction(dleConfig, BigInt(params.currentChainId || params.supportedChainIds?.[0] || 1), params.initializer || params.initialPartners?.[0] || "0x0000000000000000000000000000000000000000");
const dleInit = deployTx.data;
const initCodeHash = ethers.keccak256(dleInit);
// Используем централизованный генератор параметров конструктора
const { generateDeploymentArgs } = require('../../utils/constructorArgsGenerator');
const { dleConfig, initializer } = generateDeploymentArgs(params);
// Проверяем наличие поддерживаемых сетей
const supportedChainIds = params.supportedChainIds || [];
if (supportedChainIds.length === 0) {
throw new Error('Не указаны поддерживаемые сети (supportedChainIds)');
}
// Создаем initCode для каждой сети отдельно
const initCodes = {};
for (const chainId of supportedChainIds) {
const deployTx = await DLE.getDeployTransaction(dleConfig, initializer);
initCodes[chainId] = deployTx.data;
}
// Получаем initCodeHash из первого initCode (все должны быть одинаковые по структуре)
const firstChainId = supportedChainIds[0];
const firstInitCode = initCodes[firstChainId];
if (!firstInitCode) {
throw new Error(`InitCode не создан для первой сети: ${firstChainId}`);
}
const initCodeHash = ethers.keccak256(firstInitCode);
// DEBUG: глобальные значения
try {
const saltLen = ethers.getBytes(salt).length;
console.log(`[MULTI_DBG] GLOBAL saltLenBytes=${saltLen} salt=${salt}`);
console.log(`[MULTI_DBG] GLOBAL initCodeHash(calculated)=${initCodeHash}`);
console.log(`[MULTI_DBG] GLOBAL dleInit.lenBytes=${ethers.getBytes(dleInit).length} head16=${dleInit.slice(0, 34)}...`);
logger.info(`[MULTI_DBG] GLOBAL initCodeHash(calculated)=${initCodeHash}`);
logger.info(`[MULTI_DBG] GLOBAL firstInitCode.lenBytes=${ethers.getBytes(firstInitCode).length} head16=${firstInitCode.slice(0, 34)}...`);
} catch (e) {
console.log('[MULTI_DBG] GLOBAL precheck error', e?.message || e);
logger.info('[MULTI_DBG] GLOBAL precheck error', e?.message || e);
}
// Подготовим провайдеры и вычислим общий nonce для DLE
const providers = networks.map(u => new hre.ethers.JsonRpcProvider(u));
const wallets = providers.map(p => new hre.ethers.Wallet(pk, p));
// Подготовим провайдеры и вычислим общий nonce для DLE с retry логикой
logger.info(`[MULTI_DBG] Создаем RPC соединения для ${networks.length} сетей...`);
const connections = await createMultipleRPCConnections(networks, pk, {
maxRetries: 3,
timeout: 30000
});
if (connections.length === 0) {
throw new Error('Не удалось установить ни одного RPC соединения');
}
logger.info(`[MULTI_DBG] ✅ Успешно подключились к ${connections.length}/${networks.length} сетям`);
// Очищаем старые pending транзакции для всех сетей
for (const connection of connections) {
const chainId = Number(connection.network.chainId);
nonceManager.clearOldPendingTransactions(connection.wallet.address, chainId);
}
const nonces = [];
for (let i = 0; i < providers.length; i++) {
const n = await providers[i].getTransactionCount(wallets[i].address, 'pending');
for (const connection of connections) {
const n = await nonceManager.getNonce(connection.wallet.address, connection.rpcUrl, Number(connection.network.chainId));
nonces.push(n);
}
const targetDLENonce = Math.max(...nonces);
console.log(`[MULTI_DBG] nonces=${JSON.stringify(nonces)} targetDLENonce=${targetDLENonce}`);
console.log(`[MULTI_DBG] Starting deployment to ${networks.length} networks:`, networks);
logger.info(`[MULTI_DBG] nonces=${JSON.stringify(nonces)} targetDLENonce=${targetDLENonce}`);
logger.info(`[MULTI_DBG] Starting deployment to ${networks.length} networks:`, networks);
// ПАРАЛЛЕЛЬНЫЙ деплой во всех сетях одновременно
console.log(`[MULTI_DBG] Starting PARALLEL deployment to ${networks.length} networks`);
// ПАРАЛЛЕЛЬНЫЙ деплой во всех успешных сетях одновременно
console.log(`[MULTI_DBG] 🚀 ДОШЛИ ДО ПАРАЛЛЕЛЬНОГО ДЕПЛОЯ!`);
logger.info(`[MULTI_DBG] Starting PARALLEL deployment to ${connections.length} successful networks`);
logger.info(`[MULTI_DBG] 🚀 ЗАПУСКАЕМ ЦИКЛ ДЕПЛОЯ!`);
const deploymentPromises = networks.map(async (rpcUrl, i) => {
console.log(`[MULTI_DBG] 🚀 Starting deployment to network ${i + 1}/${networks.length}: ${rpcUrl}`);
const deploymentPromises = connections.map(async (connection, i) => {
const rpcUrl = connection.rpcUrl;
const chainId = Number(connection.network.chainId);
logger.info(`[MULTI_DBG] 🚀 Starting deployment to network ${i + 1}/${connections.length}: ${rpcUrl} (chainId: ${chainId})`);
try {
// Получаем chainId динамически из сети
const provider = new hre.ethers.JsonRpcProvider(rpcUrl);
const network = await provider.getNetwork();
const chainId = Number(network.chainId);
// Получаем правильный initCode для этой сети
const networkInitCode = initCodes[chainId];
if (!networkInitCode) {
throw new Error(`InitCode не найден для chainId: ${chainId}`);
}
console.log(`[MULTI_DBG] 📡 Network ${i + 1} chainId: ${chainId}`);
const r = await deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, dleInit, params);
console.log(`[MULTI_DBG] ✅ Network ${i + 1} (chainId: ${chainId}) deployment SUCCESS: ${r.address}`);
return { rpcUrl, chainId, ...r };
const r = await deployInNetwork(rpcUrl, pk, initCodeHash, targetDLENonce, networkInitCode, params);
logger.info(`[MULTI_DBG] ✅ Network ${i + 1} (chainId: ${chainId}) deployment SUCCESS: ${r.address}`);
return { rpcUrl, chainId, address: r.address, chainId: r.chainId };
} catch (error) {
console.error(`[MULTI_DBG] ❌ Network ${i + 1} deployment FAILED:`, error.message);
return { rpcUrl, error: error.message };
logger.error(`[MULTI_DBG] ❌ Network ${i + 1} deployment FAILED:`, error.message);
return { rpcUrl, chainId, error: error.message };
}
});
// Ждем завершения всех деплоев
const results = await Promise.all(deploymentPromises);
console.log(`[MULTI_DBG] All ${networks.length} deployments completed`);
logger.info(`[MULTI_DBG] All ${networks.length} deployments completed`);
// Логируем результаты для каждой сети
results.forEach((result, index) => {
if (result.address) {
console.log(`[MULTI_DBG] ✅ Network ${index + 1} (chainId: ${result.chainId}) SUCCESS: ${result.address}`);
logger.info(`[MULTI_DBG] ✅ Network ${index + 1} (chainId: ${result.chainId}) SUCCESS: ${result.address}`);
} else {
console.log(`[MULTI_DBG] ❌ Network ${index + 1} (chainId: ${result.chainId}) FAILED: ${result.error}`);
logger.info(`[MULTI_DBG] ❌ Network ${index + 1} (chainId: ${result.chainId}) FAILED: ${result.error}`);
}
});
// Проверяем, что все адреса одинаковые
// Проверяем, что все адреса одинаковые (критично для детерминированного деплоя)
const addresses = results.map(r => r.address).filter(addr => addr);
const uniqueAddresses = [...new Set(addresses)];
console.log('[MULTI_DBG] All addresses:', addresses);
console.log('[MULTI_DBG] Unique addresses:', uniqueAddresses);
console.log('[MULTI_DBG] Results count:', results.length);
console.log('[MULTI_DBG] Networks count:', networks.length);
logger.info('[MULTI_DBG] All addresses:', addresses);
logger.info('[MULTI_DBG] Unique addresses:', uniqueAddresses);
logger.info('[MULTI_DBG] Results count:', results.length);
logger.info('[MULTI_DBG] Networks count:', networks.length);
if (uniqueAddresses.length > 1) {
console.error('[MULTI_DBG] ERROR: DLE addresses are different across networks!');
console.error('[MULTI_DBG] addresses:', uniqueAddresses);
logger.error('[MULTI_DBG] ERROR: DLE addresses are different across networks!');
logger.error('[MULTI_DBG] addresses:', uniqueAddresses);
throw new Error('Nonce alignment failed - addresses are different');
}
if (uniqueAddresses.length === 0) {
console.error('[MULTI_DBG] ERROR: No successful deployments!');
logger.error('[MULTI_DBG] ERROR: No successful deployments!');
throw new Error('No successful deployments');
}
console.log('[MULTI_DBG] SUCCESS: All DLE addresses are identical:', uniqueAddresses[0]);
logger.info('[MULTI_DBG] SUCCESS: All DLE addresses are identical:', uniqueAddresses[0]);
// Автоматическая верификация контрактов
let verificationResults = [];
console.log(`[MULTI_DBG] autoVerifyAfterDeploy: ${params.autoVerifyAfterDeploy}`);
if (params.autoVerifyAfterDeploy) {
console.log('[MULTI_DBG] Starting automatic contract verification...');
try {
// Импортируем функцию верификации
const { verifyWithHardhatV2 } = require('../verify-with-hardhat-v2');
// Подготавливаем данные о развернутых сетях
const deployedNetworks = results
.filter(result => result.address && !result.error)
.map(result => ({
chainId: result.chainId,
address: result.address
}));
// Запускаем верификацию с данными о сетях
await verifyWithHardhatV2(params, deployedNetworks);
// Если верификация прошла успешно, отмечаем все как верифицированные
verificationResults = networks.map(() => 'verified');
console.log('[MULTI_DBG] ✅ Automatic verification completed successfully');
} catch (verificationError) {
console.error('[MULTI_DBG] ❌ Automatic verification failed:', verificationError.message);
verificationResults = networks.map(() => 'verification_failed');
}
} else {
console.log('[MULTI_DBG] Contract verification disabled (autoVerifyAfterDeploy: false)');
verificationResults = networks.map(() => 'disabled');
}
// Объединяем результаты
// ВЫВОДИМ РЕЗУЛЬТАТ СРАЗУ ПОСЛЕ ДЕПЛОЯ (ПЕРЕД ВЕРИФИКАЦИЕЙ)!
console.log('[MULTI_DBG] 🎯 ДОШЛИ ДО ВЫВОДА РЕЗУЛЬТАТА!');
const finalResults = results.map((result, index) => ({
...result,
verification: verificationResults[index] || 'failed'
verification: 'pending'
}));
console.log('[MULTI_DBG] 📊 finalResults:', JSON.stringify(finalResults, null, 2));
console.log('[MULTI_DBG] 🎯 ВЫВОДИМ MULTICHAIN_DEPLOY_RESULT!');
console.log('MULTICHAIN_DEPLOY_RESULT', JSON.stringify(finalResults));
console.log('[MULTI_DBG] ✅ MULTICHAIN_DEPLOY_RESULT ВЫВЕДЕН!');
logger.info('[MULTI_DBG] DLE deployment completed successfully!');
console.log('[MULTI_DBG] DLE deployment completed successfully!');
// Верификация контрактов отключена
logger.info('[MULTI_DBG] Contract verification disabled - skipping verification step');
// Отмечаем все результаты как без верификации
const finalResultsWithVerification = results.map((result) => ({
...result,
verification: 'skipped'
}));
logger.info('[MULTI_DBG] Verification skipped - deployment completed successfully');
}
main().catch((e) => { console.error(e); process.exit(1); });
console.log('[MULTI_DBG] 🚀 ВЫЗЫВАЕМ MAIN()...');
main().catch((e) => {
console.log('[MULTI_DBG] ❌ ОШИБКА В MAIN:', e);
logger.error('[MULTI_DBG] ❌ Deployment failed:', e);
// Даже при ошибке выводим результат для анализа
const errorResult = {
error: e.message,
success: false,
timestamp: new Date().toISOString(),
stack: e.stack
};
console.log('MULTICHAIN_DEPLOY_RESULT', JSON.stringify([errorResult]));
process.exit(1);
});

View File

@@ -0,0 +1,119 @@
/**
* Автоматическая генерация ABI для фронтенда
* Извлекает ABI из скомпилированных артефактов Hardhat
*/
const fs = require('fs');
const path = require('path');
// Пути к артефактам
const artifactsPath = path.join(__dirname, '../artifacts/contracts');
const frontendAbiPath = path.join(__dirname, '../../frontend/src/utils/dle-abi.js');
// Создаем директорию если она не существует
const frontendDir = path.dirname(frontendAbiPath);
if (!fs.existsSync(frontendDir)) {
fs.mkdirSync(frontendDir, { recursive: true });
console.log('✅ Создана директория:', frontendDir);
}
// Функция для извлечения ABI из артефакта
function extractABI(contractName) {
const artifactPath = path.join(artifactsPath, `${contractName}.sol`, `${contractName}.json`);
if (!fs.existsSync(artifactPath)) {
console.log(`⚠️ Артефакт не найден: ${artifactPath}`);
return null;
}
try {
const artifact = JSON.parse(fs.readFileSync(artifactPath, 'utf8'));
return artifact.abi;
} catch (error) {
console.error(`❌ Ошибка чтения артефакта ${contractName}:`, error.message);
return null;
}
}
// Функция для форматирования ABI в строку
function formatABI(abi) {
const functions = abi.filter(item => item.type === 'function');
const events = abi.filter(item => item.type === 'event');
let result = 'export const DLE_ABI = [\n';
// Функции
functions.forEach(func => {
const inputs = func.inputs.map(input => `${input.type} ${input.name}`).join(', ');
const outputs = func.outputs.map(output => output.type).join(', ');
const returns = outputs ? ` returns (${outputs})` : '';
result += ` "${func.type} ${func.name}(${inputs})${returns}",\n`;
});
// События
events.forEach(event => {
const inputs = event.inputs.map(input => `${input.type} ${input.name}`).join(', ');
result += ` "event ${event.name}(${inputs})",\n`;
});
result += '];\n';
return result;
}
// Функция для генерации полного файла ABI
function generateABIFile() {
console.log('🔨 Генерация ABI файла...');
// Извлекаем ABI для DLE контракта
const dleABI = extractABI('DLE');
if (!dleABI) {
console.error('❌ Не удалось извлечь ABI для DLE контракта');
return;
}
// Форматируем ABI
const formattedABI = formatABI(dleABI);
// Создаем полный файл
const fileContent = `/**
* ABI для DLE смарт-контракта
* АВТОМАТИЧЕСКИ СГЕНЕРИРОВАНО - НЕ РЕДАКТИРОВАТЬ ВРУЧНУЮ
* Для обновления запустите: node backend/scripts/generate-abi.js
*
* Последнее обновление: ${new Date().toISOString()}
*/
${formattedABI}
// ABI для деактивации (специальные функции) - НЕ СУЩЕСТВУЮТ В КОНТРАКТЕ
export const DLE_DEACTIVATION_ABI = [
// Эти функции не существуют в контракте DLE
];
// ABI для токенов (базовые функции)
export const TOKEN_ABI = [
"function balanceOf(address owner) view returns (uint256)",
"function decimals() view returns (uint8)",
"function totalSupply() view returns (uint256)"
];
`;
// Записываем файл
try {
fs.writeFileSync(frontendAbiPath, fileContent, 'utf8');
console.log('✅ ABI файл успешно сгенерирован:', frontendAbiPath);
console.log(`📊 Функций: ${dleABI.filter(item => item.type === 'function').length}`);
console.log(`📊 Событий: ${dleABI.filter(item => item.type === 'event').length}`);
} catch (error) {
console.error('❌ Ошибка записи ABI файла:', error.message);
}
}
// Запуск генерации
if (require.main === module) {
generateABIFile();
}
module.exports = { generateABIFile, extractABI, formatABI };

View File

@@ -0,0 +1,93 @@
/**
* Автоматическая генерация flattened контракта для верификации
* Создает DLE_flattened.sol из DLE.sol с помощью hardhat flatten
*/
const { spawn, execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
// Пути к файлам
const contractsDir = path.join(__dirname, '../contracts');
const dleContractPath = path.join(contractsDir, 'DLE.sol');
const flattenedPath = path.join(contractsDir, 'DLE_flattened.sol');
// Функция для генерации flattened контракта
function generateFlattened() {
return new Promise((resolve, reject) => {
console.log('🔨 Генерация flattened контракта...');
// Проверяем существование исходного контракта
if (!fs.existsSync(dleContractPath)) {
reject(new Error(`Исходный контракт не найден: ${dleContractPath}`));
return;
}
// Запускаем hardhat flatten с перенаправлением в файл
try {
console.log('🔨 Выполняем hardhat flatten...');
execSync(`npx hardhat flatten contracts/DLE.sol > "${flattenedPath}"`, {
cwd: path.join(__dirname, '..'),
shell: true
});
// Проверяем, что файл создался
if (fs.existsSync(flattenedPath)) {
const stats = fs.statSync(flattenedPath);
console.log('✅ Flattened контракт создан:', flattenedPath);
console.log(`📊 Размер файла: ${(stats.size / 1024).toFixed(2)} KB`);
resolve();
} else {
reject(new Error('Файл не был создан'));
}
} catch (error) {
console.error('❌ Ошибка выполнения hardhat flatten:', error.message);
reject(new Error(`Ошибка flatten: ${error.message}`));
}
});
}
// Функция для проверки актуальности
function checkFlattenedFreshness() {
if (!fs.existsSync(flattenedPath)) {
return false;
}
if (!fs.existsSync(dleContractPath)) {
return false;
}
const flattenedStats = fs.statSync(flattenedPath);
const contractStats = fs.statSync(dleContractPath);
// Flattened файл старше контракта
return flattenedStats.mtime >= contractStats.mtime;
}
// Основная функция
async function main() {
try {
console.log('🔍 Проверка актуальности flattened контракта...');
const isFresh = checkFlattenedFreshness();
if (isFresh) {
console.log('✅ Flattened контракт актуален');
return;
}
console.log('🔄 Flattened контракт устарел, генерируем новый...');
await generateFlattened();
} catch (error) {
console.error('❌ Ошибка генерации flattened контракта:', error.message);
process.exit(1);
}
}
// Запуск если вызван напрямую
if (require.main === module) {
main();
}
module.exports = { generateFlattened, checkFlattenedFreshness };

View File

@@ -1,130 +0,0 @@
/**
* Главный скрипт для запуска всех тестов
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
*/
const { spawn } = require('child_process');
const path = require('path');
console.log('🧪 ЗАПУСК ВСЕХ ТЕСТОВ ДЛЯ ВЫЯВЛЕНИЯ ПРОБЛЕМЫ');
console.log('=' .repeat(70));
const tests = [
{
name: 'Тест создания файла',
script: './test-file-creation.js',
description: 'Проверяет базовое создание и обновление файла current-params.json'
},
{
name: 'Тест полного потока деплоя',
script: './test-deploy-flow.js',
description: 'Имитирует полный процесс деплоя DLE с созданием файла'
},
{
name: 'Тест сохранения файла',
script: './test-file-persistence.js',
description: 'Проверяет сохранение файла после различных операций'
},
{
name: 'Тест обработки ошибок',
script: './test-error-handling.js',
description: 'Проверяет поведение при ошибках деплоя'
}
];
async function runTest(testInfo, index) {
return new Promise((resolve, reject) => {
console.log(`\n${index + 1}️⃣ ${testInfo.name}`);
console.log(`📝 ${testInfo.description}`);
console.log('─'.repeat(50));
const testPath = path.join(__dirname, testInfo.script);
const testProcess = spawn('node', [testPath], {
stdio: 'inherit',
cwd: __dirname
});
testProcess.on('close', (code) => {
if (code === 0) {
console.log(`${testInfo.name} - УСПЕШНО`);
resolve(true);
} else {
console.log(`${testInfo.name} - ОШИБКА (код: ${code})`);
resolve(false);
}
});
testProcess.on('error', (error) => {
console.log(`${testInfo.name} - ОШИБКА ЗАПУСКА: ${error.message}`);
resolve(false);
});
});
}
async function runAllTests() {
console.log('🚀 Запуск всех тестов...\n');
const results = [];
for (let i = 0; i < tests.length; i++) {
const result = await runTest(tests[i], i);
results.push({
name: tests[i].name,
success: result
});
// Небольшая пауза между тестами
await new Promise(resolve => setTimeout(resolve, 1000));
}
// Итоговый отчет
console.log('\n' + '='.repeat(70));
console.log('📊 ИТОГОВЫЙ ОТЧЕТ ТЕСТОВ');
console.log('='.repeat(70));
const successfulTests = results.filter(r => r.success).length;
const totalTests = results.length;
results.forEach((result, index) => {
const status = result.success ? '✅' : '❌';
console.log(`${index + 1}. ${status} ${result.name}`);
});
console.log(`\n📈 Результаты: ${successfulTests}/${totalTests} тестов прошли успешно`);
if (successfulTests === totalTests) {
console.log('🎉 ВСЕ ТЕСТЫ ПРОШЛИ УСПЕШНО!');
console.log('💡 Проблема НЕ в базовых операциях с файлами');
console.log('🔍 Возможные причины проблемы:');
console.log(' - Процесс деплоя прерывается до создания файла');
console.log(' - Ошибка в логике dleV2Service.js');
console.log(' - Проблема с правами доступа к файлам');
console.log(' - Конфликт с другими процессами');
} else {
console.log('⚠️ НЕКОТОРЫЕ ТЕСТЫ НЕ ПРОШЛИ');
console.log('🔍 Это поможет локализовать проблему');
}
console.log('\n🛠 СЛЕДУЮЩИЕ ШАГИ:');
console.log('1. Запустите: node debug-file-monitor.js (в отдельном терминале)');
console.log('2. Запустите деплой DLE в другом терминале');
console.log('3. Наблюдайте за созданием/удалением файлов в реальном времени');
console.log('4. Проверьте логи Docker: docker logs dapp-backend -f');
console.log('\n📋 ДОПОЛНИТЕЛЬНЫЕ КОМАНДЫ ДЛЯ ОТЛАДКИ:');
console.log('# Проверить права доступа к директориям:');
console.log('ls -la backend/scripts/deploy/');
console.log('ls -la backend/temp/');
console.log('');
console.log('# Проверить процессы Node.js:');
console.log('ps aux | grep node');
console.log('');
console.log('# Проверить использование диска:');
console.log('df -h backend/scripts/deploy/');
}
// Запускаем все тесты
runAllTests().catch(error => {
console.error('❌ КРИТИЧЕСКАЯ ОШИБКА:', error.message);
process.exit(1);
});

View File

@@ -1,120 +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
*/
// Устанавливаем переменные окружения для Docker
process.env.OLLAMA_BASE_URL = 'http://ollama:11434';
process.env.OLLAMA_MODEL = 'qwen2.5:7b';
const aiQueueService = require('../services/ai-queue');
async function testQueueInDocker() {
// console.log('🐳 Тестирование AI очереди в Docker...\n');
try {
// Проверяем инициализацию
// console.log('1. Проверка инициализации очереди...');
const stats = aiQueueService.getStats();
// console.log('✅ Очередь инициализирована:', stats.isInitialized);
// console.log('📊 Статистика:', {
totalProcessed: stats.totalProcessed,
totalFailed: stats.totalFailed,
currentQueueSize: stats.currentQueueSize,
runningTasks: stats.runningTasks
});
// Тестируем добавление задач
console.log('\n2. Тестирование добавления задач...');
const testTasks = [
{
message: 'Привет, как дела?',
language: 'ru',
type: 'chat',
userId: 1,
userRole: 'user',
requestId: 'docker_test_1'
},
{
message: 'Расскажи о погоде',
language: 'ru',
type: 'analysis',
userId: 1,
userRole: 'user',
requestId: 'docker_test_2'
},
{
message: 'Срочный вопрос!',
language: 'ru',
type: 'urgent',
userId: 1,
userRole: 'admin',
requestId: 'docker_test_3'
}
];
for (let i = 0; i < testTasks.length; i++) {
const task = testTasks[i];
console.log(` Добавляем задачу ${i + 1}: "${task.message}"`);
try {
const result = await aiQueueService.addTask(task);
console.log(` ✅ Задача добавлена, ID: ${result.taskId}`);
} catch (error) {
console.log(` ❌ Ошибка добавления задачи: ${error.message}`);
}
}
// Ждем обработки
console.log('\n3. Ожидание обработки задач...');
await new Promise(resolve => setTimeout(resolve, 15000));
// Проверяем статистику
console.log('\n4. Проверка статистики после обработки...');
const finalStats = aiQueueService.getStats();
console.log('📊 Финальная статистика:', {
totalProcessed: finalStats.totalProcessed,
totalFailed: finalStats.totalFailed,
currentQueueSize: finalStats.currentQueueSize,
runningTasks: finalStats.runningTasks,
averageProcessingTime: Math.round(finalStats.averageProcessingTime)
});
// Тестируем управление очередью
console.log('\n5. Тестирование управления очередью...');
console.log(' Пауза очереди...');
aiQueueService.pause();
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(' Возобновление очереди...');
aiQueueService.resume();
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('\n✅ Тестирование завершено!');
} catch (error) {
console.error('❌ Ошибка тестирования:', error);
}
}
// Запуск теста
if (require.main === module) {
testQueueInDocker().then(() => {
console.log('\n🏁 Тест завершен');
process.exit(0);
}).catch(error => {
console.error('💥 Критическая ошибка:', error);
process.exit(1);
});
}
module.exports = { testQueueInDocker };

View File

@@ -1,116 +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
*/
const aiQueueService = require('../services/ai-queue');
async function testQueue() {
console.log('🧪 Тестирование AI очереди...\n');
try {
// Проверяем инициализацию
console.log('1. Проверка инициализации очереди...');
const stats = aiQueueService.getStats();
console.log('✅ Очередь инициализирована:', stats.isInitialized);
console.log('📊 Статистика:', {
totalProcessed: stats.totalProcessed,
totalFailed: stats.totalFailed,
currentQueueSize: stats.currentQueueSize,
runningTasks: stats.runningTasks
});
// Тестируем добавление задач
console.log('\n2. Тестирование добавления задач...');
const testTasks = [
{
message: 'Привет, как дела?',
language: 'ru',
type: 'chat',
userId: 1,
userRole: 'user',
requestId: 'test_1'
},
{
message: 'Расскажи о погоде',
language: 'ru',
type: 'analysis',
userId: 1,
userRole: 'user',
requestId: 'test_2'
},
{
message: 'Срочный вопрос!',
language: 'ru',
type: 'urgent',
userId: 1,
userRole: 'admin',
requestId: 'test_3'
}
];
for (let i = 0; i < testTasks.length; i++) {
const task = testTasks[i];
console.log(` Добавляем задачу ${i + 1}: "${task.message}"`);
try {
const result = await aiQueueService.addTask(task);
console.log(` ✅ Задача добавлена, ID: ${result.taskId}`);
} catch (error) {
console.log(` ❌ Ошибка добавления задачи: ${error.message}`);
}
}
// Ждем обработки
console.log('\n3. Ожидание обработки задач...');
await new Promise(resolve => setTimeout(resolve, 10000));
// Проверяем статистику
console.log('\n4. Проверка статистики после обработки...');
const finalStats = aiQueueService.getStats();
console.log('📊 Финальная статистика:', {
totalProcessed: finalStats.totalProcessed,
totalFailed: finalStats.totalFailed,
currentQueueSize: finalStats.currentQueueSize,
runningTasks: finalStats.runningTasks,
averageProcessingTime: Math.round(finalStats.averageProcessingTime)
});
// Тестируем управление очередью
console.log('\n5. Тестирование управления очередью...');
console.log(' Пауза очереди...');
aiQueueService.pause();
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(' Возобновление очереди...');
aiQueueService.resume();
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('\n✅ Тестирование завершено!');
} catch (error) {
console.error('❌ Ошибка тестирования:', error);
}
}
// Запуск теста
if (require.main === module) {
testQueue().then(() => {
console.log('\n🏁 Тест завершен');
process.exit(0);
}).catch(error => {
console.error('💥 Критическая ошибка:', error);
process.exit(1);
});
}
module.exports = { testQueue };

View File

@@ -1,82 +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
*/
const encryptedDb = require('../services/encryptedDatabaseService');
const db = require('../db');
async function testEncryptedTables() {
console.log('🔐 Тестирование зашифрованных таблиц...\n');
try {
// Тестируем таблицу is_rag_source
console.log('1. Тестирование таблицы is_rag_source:');
const ragSources = await encryptedDb.getData('is_rag_source', {});
console.log(' ✅ Данные получены:', ragSources);
// Тестируем через прямой SQL запрос
const fs = require('fs');
const path = require('path');
let encryptionKey = 'default-key';
try {
const keyPath = path.join(__dirname, '../ssl/keys/full_db_encryption.key');
if (fs.existsSync(keyPath)) {
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
}
} catch (keyError) {
console.error('Error reading encryption key:', keyError);
}
const directResult = await db.getQuery()(
'SELECT id, decrypt_text(name_encrypted, $1) as name FROM is_rag_source ORDER BY id',
[encryptionKey]
);
console.log(' ✅ Прямой SQL запрос:', directResult.rows);
// Тестируем другие важные таблицы
console.log('\n2. Тестирование других зашифрованных таблиц:');
// user_tables
const userTables = await encryptedDb.getData('user_tables', {}, 5);
console.log(' ✅ user_tables (первые 5):', userTables.length, 'записей');
// user_columns
const userColumns = await encryptedDb.getData('user_columns', {}, 5);
console.log(' ✅ user_columns (первые 5):', userColumns.length, 'записей');
// messages
const messages = await encryptedDb.getData('messages', {}, 3);
console.log(' ✅ messages (первые 3):', messages.length, 'записей');
// conversations
const conversations = await encryptedDb.getData('conversations', {}, 3);
console.log(' ✅ conversations (первые 3):', conversations.length, 'записей');
console.log('\n✅ Все тесты прошли успешно!');
} catch (error) {
console.error('❌ Ошибка тестирования:', error);
}
}
// Запуск теста
if (require.main === module) {
testEncryptedTables().then(() => {
console.log('\n🏁 Тест завершен');
process.exit(0);
}).catch(error => {
console.error('💥 Критическая ошибка:', error);
process.exit(1);
});
}
module.exports = { testEncryptedTables };

View File

@@ -1,13 +1,207 @@
/**
* Верификация контрактов с Hardhat V2 API
* Верификация контрактов в Etherscan V2
*/
const { execSync } = require('child_process');
// const { execSync } = require('child_process'); // Удалено - больше не используем Hardhat verify
const DeployParamsService = require('../services/deployParamsService');
const deploymentWebSocketService = require('../services/deploymentWebSocketService');
const { getSecret } = require('../services/secretStore');
// Функция для определения Etherscan V2 API URL по chainId
function getEtherscanApiUrl(chainId) {
// Используем единый Etherscan V2 API для всех сетей
return `https://api.etherscan.io/v2/api?chainid=${chainId}`;
}
// Импортируем вспомогательную функцию
const { createStandardJsonInput: createStandardJsonInputHelper } = require('../utils/standardJsonInputHelper');
// Функция для создания стандартного JSON input
function createStandardJsonInput() {
const path = require('path');
const contractPath = path.join(__dirname, '../contracts/DLE.sol');
return createStandardJsonInputHelper(contractPath, 'DLE');
}
// Функция для проверки статуса верификации
async function checkVerificationStatus(chainId, guid, apiKey) {
const apiUrl = getEtherscanApiUrl(chainId);
const formData = new URLSearchParams({
apikey: apiKey,
module: 'contract',
action: 'checkverifystatus',
guid: guid
});
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
});
const result = await response.json();
return result;
} catch (error) {
console.error('❌ Ошибка при проверке статуса:', error.message);
return { status: '0', message: error.message };
}
}
// Функция для проверки реального статуса контракта в Etherscan
async function checkContractVerificationStatus(chainId, contractAddress, apiKey) {
const apiUrl = getEtherscanApiUrl(chainId);
const formData = new URLSearchParams({
apikey: apiKey,
module: 'contract',
action: 'getsourcecode',
address: contractAddress
});
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
});
const result = await response.json();
if (result.status === '1' && result.result && result.result[0]) {
const contractInfo = result.result[0];
const isVerified = contractInfo.SourceCode && contractInfo.SourceCode !== '';
console.log(`🔍 Статус контракта ${contractAddress}:`, {
isVerified: isVerified,
contractName: contractInfo.ContractName || 'Unknown',
compilerVersion: contractInfo.CompilerVersion || 'Unknown'
});
return { isVerified, contractInfo };
} else {
console.log('❌ Не удалось получить информацию о контракте:', result.message);
return { isVerified: false, error: result.message };
}
} catch (error) {
console.error('❌ Ошибка при проверке статуса контракта:', error.message);
return { isVerified: false, error: error.message };
}
}
// Функция для верификации контракта в Etherscan V2
async function verifyContractInEtherscan(chainId, contractAddress, constructorArgsHex, apiKey) {
const apiUrl = getEtherscanApiUrl(chainId);
const standardJsonInput = createStandardJsonInput();
console.log(`🔍 Верификация контракта ${contractAddress} в Etherscan V2 (chainId: ${chainId})`);
console.log(`📡 API URL: ${apiUrl}`);
const formData = new URLSearchParams({
apikey: apiKey,
module: 'contract',
action: 'verifysourcecode',
contractaddress: contractAddress,
codeformat: 'solidity-standard-json-input',
contractname: 'DLE.sol:DLE',
sourceCode: JSON.stringify(standardJsonInput),
compilerversion: 'v0.8.20+commit.a1b79de6',
optimizationUsed: '1',
runs: '0',
constructorArguements: constructorArgsHex
});
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
});
const result = await response.json();
console.log('📥 Ответ от Etherscan V2:', result);
if (result.status === '1') {
console.log('✅ Верификация отправлена в Etherscan V2!');
console.log(`📋 GUID: ${result.result}`);
// Ждем и проверяем статус верификации с повторными попытками
console.log('⏳ Ждем 15 секунд перед проверкой статуса...');
await new Promise(resolve => setTimeout(resolve, 15000));
// Проверяем статус с повторными попытками (до 3 раз)
let statusResult;
let attempts = 0;
const maxAttempts = 3;
do {
attempts++;
console.log(`📊 Проверка статуса верификации (попытка ${attempts}/${maxAttempts})...`);
statusResult = await checkVerificationStatus(chainId, result.result, apiKey);
console.log('📊 Статус верификации:', statusResult);
if (statusResult.status === '1') {
console.log('🎉 Верификация успешна!');
return { success: true, guid: result.result, message: 'Верифицировано в Etherscan V2' };
} else if (statusResult.status === '0' && statusResult.result.includes('Pending')) {
console.log('⏳ Верификация в очереди, проверяем реальный статус контракта...');
// Проверяем реальный статус контракта в Etherscan
const contractStatus = await checkContractVerificationStatus(chainId, contractAddress, apiKey);
if (contractStatus.isVerified) {
console.log('✅ Контракт уже верифицирован в Etherscan!');
return { success: true, guid: result.result, message: 'Контракт верифицирован' };
} else {
console.log('⏳ Контракт еще не верифицирован, ожидаем завершения...');
if (attempts < maxAttempts) {
console.log(`⏳ Ждем еще 10 секунд перед следующей попыткой...`);
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
} else {
console.log('❌ Верификация не удалась:', statusResult.result);
return { success: false, error: statusResult.result };
}
} while (attempts < maxAttempts && statusResult.status === '0' && statusResult.result.includes('Pending'));
// Если все попытки исчерпаны
if (attempts >= maxAttempts) {
console.log('⏳ Максимальное количество попыток достигнуто, верификация может быть в процессе...');
return { success: false, error: 'Ожидание верификации', guid: result.result };
}
} else {
console.log('❌ Ошибка отправки верификации в Etherscan V2:', result.message);
// Проверяем, не верифицирован ли уже контракт
if (result.message && result.message.includes('already verified')) {
console.log('✅ Контракт уже верифицирован');
return { success: true, message: 'Контракт уже верифицирован' };
}
return { success: false, error: result.message };
}
} catch (error) {
console.error('❌ Ошибка при отправке запроса в Etherscan V2:', error.message);
// Проверяем, не является ли это ошибкой сети
if (error.message.includes('fetch') || error.message.includes('network')) {
console.log('⚠️ Ошибка сети, верификация может быть в процессе...');
return { success: false, error: 'Network error - verification may be in progress' };
}
return { success: false, error: error.message };
}
}
async function verifyWithHardhatV2(params = null, deployedNetworks = null) {
console.log('🚀 Запуск верификации с Hardhat V2...');
console.log('🚀 Запуск верификации контрактов...');
try {
// Если параметры не переданы, получаем их из базы данных
@@ -23,10 +217,15 @@ async function verifyWithHardhatV2(params = null, deployedNetworks = null) {
params = latestParams[0];
}
if (!params.etherscan_api_key) {
throw new Error('Etherscan API ключ не найден в параметрах');
// Проверяем API ключ в параметрах или переменной окружения
const etherscanApiKey = params.etherscan_api_key || process.env.ETHERSCAN_API_KEY;
if (!etherscanApiKey) {
throw new Error('Etherscan API ключ не найден в параметрах или переменной окружения');
}
// Устанавливаем API ключ в переменную окружения для использования в коде
process.env.ETHERSCAN_API_KEY = etherscanApiKey;
console.log('📋 Параметры деплоя:', {
deploymentId: params.deployment_id,
name: params.name,
@@ -54,38 +253,35 @@ async function verifyWithHardhatV2(params = null, deployedNetworks = null) {
}
console.log(`🌐 Найдено ${networks.length} развернутых сетей`);
// Маппинг chainId на названия сетей
const networkMap = {
1: 'mainnet',
11155111: 'sepolia',
17000: 'holesky',
137: 'polygon',
42161: 'arbitrumOne',
421614: 'arbitrumSepolia',
56: 'bsc',
8453: 'base',
84532: 'baseSepolia'
};
// Получаем маппинг chainId на названия сетей из параметров деплоя
const networkMap = {};
if (params.supportedChainIds && params.supportedChainIds.length > 0) {
// Создаем маппинг только для поддерживаемых сетей
for (const chainId of params.supportedChainIds) {
switch (chainId) {
case 1: networkMap[chainId] = 'mainnet'; break;
case 11155111: networkMap[chainId] = 'sepolia'; break;
case 17000: networkMap[chainId] = 'holesky'; break;
case 137: networkMap[chainId] = 'polygon'; break;
case 42161: networkMap[chainId] = 'arbitrumOne'; break;
case 421614: networkMap[chainId] = 'arbitrumSepolia'; break;
case 56: networkMap[chainId] = 'bsc'; break;
case 8453: networkMap[chainId] = 'base'; break;
case 84532: networkMap[chainId] = 'baseSepolia'; break;
default: networkMap[chainId] = `chain-${chainId}`; break;
}
}
} else {
// Fallback для совместимости
networkMap[11155111] = 'sepolia';
networkMap[17000] = 'holesky';
networkMap[421614] = 'arbitrumSepolia';
networkMap[84532] = 'baseSepolia';
}
// Подготавливаем аргументы конструктора
const constructorArgs = [
{
name: params.name || '',
symbol: params.symbol || '',
location: params.location || '',
coordinates: params.coordinates || '',
jurisdiction: params.jurisdiction || 0,
oktmo: params.oktmo || '',
okvedCodes: params.okvedCodes || [],
kpp: params.kpp ? params.kpp : 0,
quorumPercentage: params.quorumPercentage || 51,
initialPartners: params.initialPartners || [],
initialAmounts: (params.initialAmounts || []).map(amount => (parseFloat(amount) * 10**18).toString()),
supportedChainIds: (params.supportedChainIds || []).map(id => id.toString())
},
(params.currentChainId || params.supportedChainIds?.[0] || 1).toString(),
params.initializer || params.initialPartners?.[0] || "0x0000000000000000000000000000000000000000"
];
// Используем централизованный генератор параметров конструктора
const { generateVerificationArgs } = require('../utils/constructorArgsGenerator');
const constructorArgs = generateVerificationArgs(params);
console.log('📊 Аргументы конструктора подготовлены');
@@ -125,77 +321,61 @@ async function verifyWithHardhatV2(params = null, deployedNetworks = null) {
await new Promise(resolve => setTimeout(resolve, 5000));
}
// Создаем временный файл с аргументами конструктора
const fs = require('fs');
const path = require('path');
const argsFile = path.join(__dirname, `constructor-args-${Date.now()}.json`);
try {
fs.writeFileSync(argsFile, JSON.stringify(constructorArgs, null, 2));
// Формируем команду верификации с файлом аргументов
const command = `ETHERSCAN_API_KEY="${params.etherscan_api_key}" npx hardhat verify --network ${networkName} ${address} --constructor-args ${argsFile}`;
console.log(`💻 Выполняем команду: npx hardhat verify --network ${networkName} ${address} --constructor-args ${argsFile}`);
const output = execSync(command, {
cwd: '/app',
encoding: 'utf8',
stdio: 'pipe'
// Получаем API ключ Etherscan
const etherscanApiKey = process.env.ETHERSCAN_API_KEY;
if (!etherscanApiKey) {
console.log('❌ API ключ Etherscan не найден, пропускаем верификацию в Etherscan');
verificationResults.push({
success: false,
network: networkName,
chainId: chainId,
error: 'No Etherscan API key'
});
console.log('✅ Верификация успешна:');
console.log(output);
continue;
}
// Кодируем аргументы конструктора в hex
const { ethers } = require('ethers');
const abiCoder = ethers.AbiCoder.defaultAbiCoder();
// Используем централизованный генератор параметров конструктора
const { generateDeploymentArgs } = require('../utils/constructorArgsGenerator');
const { dleConfig, initializer } = generateDeploymentArgs(params);
const encodedArgs = abiCoder.encode(
[
'tuple(string name, string symbol, string location, string coordinates, uint256 jurisdiction, string[] okvedCodes, uint256 kpp, uint256 quorumPercentage, address[] initialPartners, uint256[] initialAmounts, uint256[] supportedChainIds)',
'address'
],
[
dleConfig,
initializer
]
);
const constructorArgsHex = encodedArgs.slice(2); // Убираем 0x
// Верификация в Etherscan
console.log('🌐 Верификация в Etherscan...');
const etherscanResult = await verifyContractInEtherscan(chainId, address, constructorArgsHex, etherscanApiKey);
if (etherscanResult.success) {
console.log('✅ Верификация в Etherscan успешна!');
verificationResults.push({
success: true,
network: networkName,
chainId: chainId
chainId: chainId,
etherscan: true,
message: etherscanResult.message
});
} else {
console.log('❌ Ошибка верификации в Etherscan:', etherscanResult.error);
verificationResults.push({
success: false,
network: networkName,
chainId: chainId,
error: etherscanResult.error
});
// Удаляем временный файл
try {
fs.unlinkSync(argsFile);
} catch (e) {
console.log(`⚠️ Не удалось удалить временный файл: ${argsFile}`);
}
} catch (error) {
// Удаляем временный файл в случае ошибки
try {
fs.unlinkSync(argsFile);
} catch (e) {
console.log(`⚠️ Не удалось удалить временный файл: ${argsFile}`);
}
const errorOutput = error.stdout || error.stderr || error.message;
console.log('📥 Вывод команды:');
console.log(errorOutput);
if (errorOutput.includes('Already Verified')) {
console.log(' Контракт уже верифицирован');
verificationResults.push({
success: true,
network: networkName,
chainId: chainId,
alreadyVerified: true
});
} else if (errorOutput.includes('Successfully verified')) {
console.log('✅ Контракт успешно верифицирован!');
verificationResults.push({
success: true,
network: networkName,
chainId: chainId
});
} else {
console.log('❌ Ошибка верификации');
verificationResults.push({
success: false,
network: networkName,
chainId: chainId,
error: errorOutput
});
}
}
}
@@ -203,17 +383,20 @@ async function verifyWithHardhatV2(params = null, deployedNetworks = null) {
console.log('\n📊 Итоговые результаты верификации:');
const successful = verificationResults.filter(r => r.success).length;
const failed = verificationResults.filter(r => !r.success).length;
const alreadyVerified = verificationResults.filter(r => r.alreadyVerified).length;
const etherscanVerified = verificationResults.filter(r => r.etherscan).length;
console.log(`✅ Успешно верифицировано: ${successful}`);
console.log(` Уже было верифицировано: ${alreadyVerified}`);
console.log(`🌐 В Etherscan: ${etherscanVerified}`);
console.log(`❌ Ошибки: ${failed}`);
verificationResults.forEach(result => {
const status = result.success
? (result.alreadyVerified ? '' : '✅')
: '❌';
console.log(`${status} ${result.network} (${result.chainId}): ${result.success ? 'OK' : result.error?.substring(0, 100) + '...'}`);
const status = result.success ? '✅' : '❌';
const message = result.success
? (result.message || 'OK')
: result.error?.substring(0, 100) + '...';
console.log(`${status} ${result.network} (${result.chainId}): ${message}`);
});
console.log('\n🎉 Верификация завершена!');
@@ -327,13 +510,26 @@ async function verifyModules() {
}
};
// Маппинг chainId на названия сетей для Hardhat
const networkMap = {
11155111: 'sepolia',
17000: 'holesky',
421614: 'arbitrumSepolia',
84532: 'baseSepolia'
};
// Получаем маппинг chainId на названия сетей из параметров деплоя
const networkMap = {};
if (params.supportedChainIds && params.supportedChainIds.length > 0) {
// Создаем маппинг только для поддерживаемых сетей
for (const chainId of params.supportedChainIds) {
switch (chainId) {
case 11155111: networkMap[chainId] = 'sepolia'; break;
case 17000: networkMap[chainId] = 'holesky'; break;
case 421614: networkMap[chainId] = 'arbitrumSepolia'; break;
case 84532: networkMap[chainId] = 'baseSepolia'; break;
default: networkMap[chainId] = `chain-${chainId}`; break;
}
}
} else {
// Fallback для совместимости
networkMap[11155111] = 'sepolia';
networkMap[17000] = 'holesky';
networkMap[421614] = 'arbitrumSepolia';
networkMap[84532] = 'baseSepolia';
}
// Верифицируем каждый модуль
for (const file of moduleFiles) {
@@ -375,29 +571,12 @@ async function verifyModules() {
const argsFile = path.join(__dirname, `temp-args-${Date.now()}.json`);
fs.writeFileSync(argsFile, JSON.stringify(constructorArgs, null, 2));
// Выполняем верификацию
const command = `ETHERSCAN_API_KEY="${params.etherscan_api_key}" npx hardhat verify --network ${networkName} ${network.address} --constructor-args ${argsFile}`;
console.log(`📝 Команда верификации: npx hardhat verify --network ${networkName} ${network.address} --constructor-args ${argsFile}`);
// Верификация модулей через Etherscan V2 API (пока не реализовано)
console.log(`⚠️ Верификация модулей через Etherscan V2 API пока не реализована для ${moduleData.moduleType} в ${networkName}`);
try {
const output = execSync(command, {
cwd: '/app',
encoding: 'utf8',
stdio: 'pipe'
});
console.log(`${moduleData.moduleType} успешно верифицирован в ${networkName}`);
console.log(output);
// Уведомляем WebSocket клиентов о успешной верификации
deploymentWebSocketService.addDeploymentLog(dleAddress, 'success', `Модуль ${moduleData.moduleType} верифицирован в ${networkName}`);
deploymentWebSocketService.notifyModuleVerified(dleAddress, moduleData.moduleType, networkName);
} catch (verifyError) {
console.log(`❌ Ошибка верификации ${moduleData.moduleType} в ${networkName}: ${verifyError.message}`);
} finally {
// Удаляем временный файл
if (fs.existsSync(argsFile)) {
fs.unlinkSync(argsFile);
}
// Удаляем временный файл
if (fs.existsSync(argsFile)) {
fs.unlinkSync(argsFile);
}
} catch (error) {