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

This commit is contained in:
2025-08-29 18:37:57 +03:00
parent 8e50c6c4d8
commit 4e4cb611a1
53 changed files with 4380 additions and 5902 deletions

View File

@@ -1,299 +0,0 @@
/* eslint-disable no-console */
const hre = require('hardhat');
async function main() {
const { ethers } = hre;
const rpcUrl = process.env.RPC_URL;
const pk = process.env.PRIVATE_KEY;
if (!rpcUrl || !pk) throw new Error('RPC_URL/PRIVATE_KEY required');
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(pk, provider);
const salt = process.env.CREATE2_SALT;
const initCodeHash = process.env.INIT_CODE_HASH;
let factoryAddress = process.env.FACTORY_ADDRESS;
if (!salt || !initCodeHash) throw new Error('CREATE2_SALT/INIT_CODE_HASH required');
// Ensure factory
if (!factoryAddress) {
const Factory = await hre.ethers.getContractFactory('FactoryDeployer', wallet);
const factory = await Factory.deploy();
await factory.waitForDeployment();
factoryAddress = await factory.getAddress();
} else {
const code = await provider.getCode(factoryAddress);
if (code === '0x') {
const Factory = await hre.ethers.getContractFactory('FactoryDeployer', wallet);
const factory = await Factory.deploy();
await factory.waitForDeployment();
factoryAddress = await factory.getAddress();
}
}
// Prepare DLE init code = creation bytecode WITH constructor args
const DLE = await hre.ethers.getContractFactory('DLE', wallet);
const paramsPath = require('path').join(__dirname, './current-params.json');
const params = require(paramsPath);
const dleConfig = {
name: params.name,
symbol: params.symbol,
location: params.location,
coordinates: params.coordinates,
jurisdiction: params.jurisdiction,
okvedCodes: params.okvedCodes || [],
kpp: params.kpp,
quorumPercentage: params.quorumPercentage,
initialPartners: params.initialPartners,
initialAmounts: params.initialAmounts,
supportedChainIds: params.supportedChainIds
};
const deployTx = await DLE.getDeployTransaction(dleConfig, params.currentChainId);
const dleInit = deployTx.data; // полноценный init code
// Deploy via factory
const Factory = await hre.ethers.getContractAt('FactoryDeployer', factoryAddress, wallet);
const tx = await Factory.deploy(salt, dleInit);
const rc = await tx.wait();
const addr = rc.logs?.[0]?.args?.addr || (await Factory.computeAddress(salt, initCodeHash));
console.log('DLE v2 задеплоен по адресу:', addr);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
/**
* 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
*/
// Скрипт для создания современного DLE v2 (единый контракт)
const { ethers } = require("hardhat");
const fs = require("fs");
const path = require("path");
async function main() {
// Получаем параметры деплоя из файла
const deployParams = getDeployParams();
console.log("Начинаем создание современного DLE v2...");
console.log("Параметры DLE:");
console.log(JSON.stringify(deployParams, null, 2));
// Преобразуем initialAmounts в wei
const initialAmountsInWei = deployParams.initialAmounts.map(amount => ethers.parseUnits(amount.toString(), 18));
console.log("Initial amounts в wei:");
console.log(initialAmountsInWei.map(wei => ethers.formatUnits(wei, 18) + " токенов"));
// Получаем RPC URL и приватный ключ из переменных окружения
const rpcUrl = process.env.RPC_URL;
const privateKey = process.env.PRIVATE_KEY;
if (!rpcUrl || !privateKey) {
throw new Error('RPC_URL и PRIVATE_KEY должны быть установлены в переменных окружения');
}
// Создаем провайдер и кошелек
const provider = new ethers.JsonRpcProvider(rpcUrl);
const deployer = new ethers.Wallet(privateKey, provider);
console.log(`Адрес деплоера: ${deployer.address}`);
const balance = await provider.getBalance(deployer.address);
console.log(`Баланс деплоера: ${ethers.formatEther(balance)} ETH`);
// Проверяем, достаточно ли баланса для деплоя (минимум 0.00001 ETH для тестирования)
const minBalance = ethers.parseEther("0.00001");
if (balance < minBalance) {
throw new Error(`Недостаточно ETH для деплоя. Баланс: ${ethers.formatEther(balance)} ETH, требуется минимум: ${ethers.formatEther(minBalance)} ETH. Пополните кошелек через Sepolia faucet.`);
}
try {
// 1. Создаем единый контракт DLE
console.log("\n1. Деплой единого контракта DLE v2...");
const DLE = await ethers.getContractFactory("DLE", deployer);
// Создаем структуру DLEConfig с полными данными
const dleConfig = {
name: deployParams.name,
symbol: deployParams.symbol,
location: deployParams.location,
coordinates: deployParams.coordinates || "0,0",
jurisdiction: deployParams.jurisdiction || 1,
oktmo: parseInt(deployParams.oktmo) || 45000000000,
okvedCodes: deployParams.okvedCodes || [],
kpp: parseInt(deployParams.kpp) || 770101001,
quorumPercentage: deployParams.quorumPercentage || 51,
initialPartners: deployParams.initialPartners,
initialAmounts: deployParams.initialAmounts.map(amount => ethers.parseUnits(amount.toString(), 18)),
supportedChainIds: deployParams.supportedChainIds || [1, 137, 56, 42161] // Ethereum, Polygon, BSC, Arbitrum
};
console.log("Конфигурация DLE для записи в блокчейн:");
console.log("Название:", dleConfig.name);
console.log("Символ:", dleConfig.symbol);
console.log("Местонахождение:", dleConfig.location);
console.log("Координаты:", dleConfig.coordinates);
console.log("Юрисдикция:", dleConfig.jurisdiction);
console.log("ОКТМО:", dleConfig.oktmo);
console.log("Коды ОКВЭД:", dleConfig.okvedCodes.join(', '));
console.log("КПП:", dleConfig.kpp);
console.log("Кворум:", dleConfig.quorumPercentage + "%");
console.log("Партнеры:", dleConfig.initialPartners.join(', '));
console.log("Количества токенов:", dleConfig.initialAmounts.map(amount => ethers.formatUnits(amount, 18) + " токенов").join(', '));
console.log("Поддерживаемые сети:", dleConfig.supportedChainIds.join(', '));
const currentChainId = deployParams.currentChainId || 1; // По умолчанию Ethereum
const dle = await DLE.deploy(dleConfig, currentChainId);
await dle.waitForDeployment();
const dleAddress = await dle.getAddress();
console.log(`DLE v2 задеплоен по адресу: ${dleAddress}`);
// 2. Получаем информацию о DLE из блокчейна
const dleInfo = await dle.getDLEInfo();
console.log("\n2. Информация о DLE из блокчейна:");
console.log(`Название: ${dleInfo.name}`);
console.log(`Символ: ${dleInfo.symbol}`);
console.log(`Местонахождение: ${dleInfo.location}`);
console.log(`Координаты: ${dleInfo.coordinates}`);
console.log(`Юрисдикция: ${dleInfo.jurisdiction}`);
console.log(`ОКТМО: ${dleInfo.oktmo}`);
console.log(`Коды ОКВЭД: ${dleInfo.okvedCodes.join(', ')}`);
console.log(`КПП: ${dleInfo.kpp}`);
console.log(`Дата создания: ${new Date(Number(dleInfo.creationTimestamp) * 1000).toISOString()}`);
console.log(`Активен: ${dleInfo.isActive}`);
// Проверяем, что данные записались правильно
console.log("\n3. Проверка записи данных в блокчейн:");
if (dleInfo.name === deployParams.name &&
dleInfo.location === deployParams.location &&
dleInfo.jurisdiction === deployParams.jurisdiction) {
console.log("✅ Все данные DLE успешно записаны в блокчейн!");
console.log("Теперь эти данные видны на Etherscan в разделе 'Contract' -> 'Read Contract'");
} else {
console.log("❌ Ошибка: данные не записались правильно в блокчейн");
}
// 4. Сохраняем информацию о созданном DLE
console.log("\n4. Сохранение информации о DLE v2...");
const dleData = {
name: deployParams.name,
symbol: deployParams.symbol,
location: deployParams.location,
coordinates: deployParams.coordinates || "0,0",
jurisdiction: deployParams.jurisdiction || 1,
oktmo: deployParams.oktmo || 45000000000,
okvedCodes: deployParams.okvedCodes || [],
kpp: deployParams.kpp || 770101001,
dleAddress: dleAddress,
creationBlock: Number(await provider.getBlockNumber()),
creationTimestamp: Number((await provider.getBlock()).timestamp),
deployedManually: true,
version: "v2",
// Сохраняем информацию о партнерах
initialPartners: deployParams.initialPartners || [],
initialAmounts: deployParams.initialAmounts || [],
governanceSettings: {
quorumPercentage: deployParams.quorumPercentage || 51,
supportedChainIds: deployParams.supportedChainIds || [1, 137, 56, 42161],
currentChainId: currentChainId
}
};
const saveResult = saveDLEData(dleData);
console.log("\nDLE v2 успешно создан!");
console.log(`Адрес DLE: ${dleAddress}`);
console.log(`Версия: v2 (единый контракт)`);
return {
success: true,
dleAddress: dleAddress,
data: dleData
};
} catch (error) {
console.error("Ошибка при создании DLE v2:", error);
throw error;
}
}
// Получаем параметры деплоя из файла
function getDeployParams() {
const paramsFile = path.join(__dirname, 'current-params.json');
if (!fs.existsSync(paramsFile)) {
console.error(`Файл параметров не найден: ${paramsFile}`);
process.exit(1);
}
try {
const params = JSON.parse(fs.readFileSync(paramsFile, 'utf8'));
console.log("Параметры загружены из файла");
return params;
} catch (error) {
console.error("Ошибка при чтении файла параметров:", error);
process.exit(1);
}
}
// Сохраняем информацию о созданном DLE
function saveDLEData(dleData) {
const dlesDir = path.join(__dirname, "../../contracts-data/dles");
// Проверяем существование директории и создаем при необходимости
try {
if (!fs.existsSync(dlesDir)) {
console.log(`Директория ${dlesDir} не существует, создаю...`);
fs.mkdirSync(dlesDir, { recursive: true });
console.log(`Директория ${dlesDir} успешно создана`);
}
// Проверяем права на запись, создавая временный файл
const testFile = path.join(dlesDir, '.write-test');
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
console.log(`Директория ${dlesDir} доступна для записи`);
} catch (error) {
console.error(`Ошибка при проверке директории ${dlesDir}:`, error);
throw error;
}
// Создаем уникальное имя файла
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = `dle-v2-${timestamp}.json`;
const filePath = path.join(dlesDir, fileName);
try {
fs.writeFileSync(filePath, JSON.stringify(dleData, null, 2));
console.log(`Информация о DLE сохранена в файл: ${fileName}`);
return { success: true, filePath };
} catch (error) {
console.error(`Ошибка при сохранении файла ${filePath}:`, error);
throw error;
}
}
// Запускаем скрипт
main()
.then(() => {
console.log("Скрипт завершен успешно");
process.exit(0);
})
.catch((error) => {
console.error("Скрипт завершен с ошибкой:", error);
process.exit(1);
});

View File

@@ -1,6 +1,7 @@
/* eslint-disable no-console */
const hre = require('hardhat');
const path = require('path');
const fs = require('fs');
// Подбираем безопасные gas/fee для разных сетей (включая L2)
async function getFeeOverrides(provider, { minPriorityGwei = 1n, minFeeGwei = 20n } = {}) {
@@ -19,7 +20,7 @@ async function getFeeOverrides(provider, { minPriorityGwei = 1n, minFeeGwei = 20
return overrides;
}
async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetFactoryNonce, dleInit) {
async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, dleInit) {
const { ethers } = hre;
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(pk, provider);
@@ -30,7 +31,7 @@ async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetFactoryNonc
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} targetFactoryNonce=${targetFactoryNonce}`);
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}`);
@@ -39,170 +40,195 @@ async function deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetFactoryNonc
console.log('[MULTI_DBG] precheck error', e?.message || e);
}
// 1) Выравнивание nonce до targetFactoryNonce нулевыми транзакциями (если нужно)
// 1) Выравнивание nonce до targetDLENonce нулевыми транзакциями (если нужно)
let current = await provider.getTransactionCount(wallet.address, 'pending');
if (current > targetFactoryNonce) {
throw new Error(`Current nonce ${current} > targetFactoryNonce ${targetFactoryNonce} on chainId=${Number(net.chainId)}`);
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} current nonce=${current} target=${targetDLENonce}`);
if (current > targetDLENonce) {
throw new Error(`Current nonce ${current} > targetDLENonce ${targetDLENonce} on chainId=${Number(net.chainId)}`);
}
while (current < targetFactoryNonce) {
const overrides = await getFeeOverrides(provider);
let gasLimit = 50000; // некоторые L2 требуют >21000
let sent = false;
let lastErr = null;
for (let attempt = 0; attempt < 2 && !sent; attempt++) {
try {
const txReq = {
to: wallet.address,
value: 0n,
nonce: current,
gasLimit,
...overrides
};
const txFill = await wallet.sendTransaction(txReq);
await txFill.wait();
sent = true;
} catch (e) {
lastErr = e;
if (String(e?.message || '').toLowerCase().includes('intrinsic gas too low') && attempt === 0) {
gasLimit = 100000; // поднимаем лимит и пробуем ещё раз
continue;
if (current < targetDLENonce) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} aligning nonce from ${current} to ${targetDLENonce} (${targetDLENonce - current} transactions needed)`);
// Используем burn address для более надежных транзакций
const burnAddress = "0x000000000000000000000000000000000000dEaD";
while (current < targetDLENonce) {
const overrides = await getFeeOverrides(provider);
let gasLimit = 21000; // минимальный gas для обычной транзакции
let sent = false;
let lastErr = null;
for (let attempt = 0; attempt < 3 && !sent; attempt++) {
try {
const txReq = {
to: burnAddress, // отправляем на burn address вместо своего адреса
value: 0n,
nonce: current,
gasLimit,
...overrides
};
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} sending filler tx nonce=${current} attempt=${attempt + 1}`);
const txFill = await wallet.sendTransaction(txReq);
await txFill.wait();
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} filler tx nonce=${current} confirmed`);
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}`);
if (String(e?.message || '').toLowerCase().includes('intrinsic gas too low') && attempt < 2) {
gasLimit = 50000; // увеличиваем gas limit
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}`);
continue;
}
throw e;
}
throw e;
}
if (!sent) {
console.error(`[MULTI_DBG] chainId=${Number(net.chainId)} failed to send filler tx for nonce=${current}`);
throw lastErr || new Error('filler tx failed');
}
current++;
}
if (!sent) throw lastErr || new Error('filler tx failed');
current++;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce alignment completed, current nonce=${current}`);
} else {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} nonce already aligned at ${current}`);
}
// 2) Деплой FactoryDeployer на согласованном nonce
const FactoryCF = await hre.ethers.getContractFactory('FactoryDeployer', wallet);
// 2) Деплой DLE напрямую на согласованном nonce
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} deploying DLE directly with nonce=${targetDLENonce}`);
const feeOverrides = await getFeeOverrides(provider);
const factoryContract = await FactoryCF.deploy({ nonce: targetFactoryNonce, ...feeOverrides });
await factoryContract.waitForDeployment();
const factoryAddress = await factoryContract.getAddress();
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} FactoryDeployer.address=${factoryAddress}`);
let gasLimit;
try {
// Оцениваем газ для деплоя DLE
const est = await wallet.estimateGas({ data: dleInit, ...feeOverrides }).catch(() => null);
// Рассчитываем доступный gasLimit из баланса
const balance = await provider.getBalance(wallet.address, 'latest');
const effPrice = feeOverrides.maxFeePerGas || feeOverrides.gasPrice || 0n;
const reserve = hre.ethers.parseEther('0.005');
const maxByBalance = effPrice > 0n && balance > reserve ? (balance - reserve) / effPrice : 3_000_000n;
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()}`);
} catch (_) {
gasLimit = 3_000_000n;
}
// 3) Деплой DLE через CREATE2
const Factory = await hre.ethers.getContractAt('FactoryDeployer', factoryAddress, wallet);
const n = await provider.getTransactionCount(wallet.address, 'pending');
// Вычисляем предсказанный адрес DLE
const predictedAddress = ethers.getCreateAddress({
from: wallet.address,
nonce: targetDLENonce
});
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} predicted DLE address=${predictedAddress}`);
// Проверяем, не развернут ли уже контракт
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`);
return { address: predictedAddress, chainId: Number(net.chainId) };
}
// Деплоим DLE
let tx;
try {
// Предварительная проверка конструктора вне CREATE2 (даст явную причину, если он ревертится)
try {
await wallet.estimateGas({ data: dleInit });
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} predeploy(estGas) ok for constructor`);
} catch (e) {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} predeploy(estGas) failed: ${e?.reason || e?.shortMessage || e?.message || e}`);
if (e?.data) console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} predeploy revert data: ${e.data}`);
}
// Оцениваем газ и добавляем запас
const est = await Factory.deploy.estimateGas(salt, dleInit, { nonce: n, ...feeOverrides }).catch(() => null);
// Рассчитываем доступный gasLimit из баланса
let gasLimit;
try {
const balance = await provider.getBalance(wallet.address, 'latest');
const effPrice = feeOverrides.maxFeePerGas || feeOverrides.gasPrice || 0n;
const reserve = hre.ethers.parseEther('0.005');
const maxByBalance = effPrice > 0n && balance > reserve ? (balance - reserve) / effPrice : 3_000_000n;
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()}`);
} catch (_) {
const fallbackGas = 3_000_000n;
gasLimit = est ? (est + est / 5n) : fallbackGas;
}
// DEBUG: ожидаемый адрес через computeAddress
try {
const predicted = await Factory.computeAddress(salt, initCodeHash);
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} predictedAddress=${predicted}`);
// Idempotency: если уже есть код по адресу, пропускаем деплой
const code = await provider.getCode(predicted);
if (code && code !== '0x') {
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} code already exists at predictedAddress, skip deploy`);
return { factory: factoryAddress, address: predicted, chainId: Number(net.chainId) };
}
} catch (e) {
console.log('[MULTI_DBG] computeAddress(before) error', e?.message || e);
}
tx = await Factory.deploy(salt, dleInit, { nonce: n, gasLimit, ...feeOverrides });
tx = await wallet.sendTransaction({
data: dleInit,
nonce: targetDLENonce,
gasLimit,
...feeOverrides
});
} catch (e) {
const n2 = await provider.getTransactionCount(wallet.address, 'pending');
const est2 = await Factory.deploy.estimateGas(salt, dleInit, { nonce: n2, ...feeOverrides }).catch(() => null);
let gasLimit2;
try {
const balance2 = await provider.getBalance(wallet.address, 'latest');
const effPrice2 = feeOverrides.maxFeePerGas || feeOverrides.gasPrice || 0n;
const reserve2 = hre.ethers.parseEther('0.005');
const maxByBalance2 = effPrice2 > 0n && balance2 > reserve2 ? (balance2 - reserve2) / effPrice2 : 3_000_000n;
const fallbackGas2 = maxByBalance2 > 5_000_000n ? 5_000_000n : (maxByBalance2 < 2_500_000n ? 2_500_000n : maxByBalance2);
gasLimit2 = est2 ? (est2 + est2 / 5n) : fallbackGas2;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} RETRY estGas=${est2?.toString?.()||'null'} effGasPrice=${effPrice2?.toString?.()||'0'} maxByBalance=${maxByBalance2.toString()} chosenGasLimit=${gasLimit2.toString()}`);
} catch (_) {
gasLimit2 = est2 ? (est2 + est2 / 5n) : 3_000_000n;
}
console.log(`[MULTI_DBG] retry deploy with nonce=${n2} gasLimit=${gasLimit2?.toString?.() || 'auto'}`);
console.log(`[MULTI_DBG] deploy error(first) ${e?.message || e}`);
tx = await Factory.deploy(salt, dleInit, { nonce: n2, gasLimit: gasLimit2, ...feeOverrides });
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
});
}
const rc = await tx.wait();
let addr = rc.logs?.[0]?.args?.addr;
if (!addr) {
try {
addr = await Factory.computeAddress(salt, initCodeHash);
} catch (e) {
console.log('[MULTI_DBG] computeAddress(after) error', e?.message || e);
}
}
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} deployedAddress=${addr}`);
return { factory: factoryAddress, address: addr, chainId: Number(net.chainId) };
const deployedAddress = rc.contractAddress || predictedAddress;
console.log(`[MULTI_DBG] chainId=${Number(net.chainId)} DLE deployed at=${deployedAddress}`);
return { address: deployedAddress, chainId: Number(net.chainId) };
}
async function main() {
const { ethers } = hre;
const pk = process.env.PRIVATE_KEY;
const salt = process.env.CREATE2_SALT;
const initCodeHash = process.env.INIT_CODE_HASH;
const networks = (process.env.MULTICHAIN_RPC_URLS || '').split(',').map(s => s.trim()).filter(Boolean);
const factories = (process.env.MULTICHAIN_FACTORY_ADDRESSES || '').split(',').map(s => s.trim());
if (!pk) throw new Error('Env: PRIVATE_KEY');
if (!salt) throw new Error('Env: CREATE2_SALT');
if (!initCodeHash) throw new Error('Env: INIT_CODE_HASH');
if (networks.length === 0) throw new Error('Env: MULTICHAIN_RPC_URLS');
// Prepare init code once
// Загружаем параметры из файла
const paramsPath = path.join(__dirname, './current-params.json');
const params = require(paramsPath);
const DLE = await hre.ethers.getContractFactory('DLE');
const dleConfig = {
if (!fs.existsSync(paramsPath)) {
throw new Error('Файл параметров не найден: ' + paramsPath);
}
const params = JSON.parse(fs.readFileSync(paramsPath, 'utf8'));
console.log('[MULTI_DBG] Загружены параметры:', {
name: params.name,
symbol: params.symbol,
location: params.location,
coordinates: params.coordinates,
jurisdiction: params.jurisdiction,
oktmo: params.oktmo,
supportedChainIds: params.supportedChainIds,
CREATE2_SALT: params.CREATE2_SALT
});
const pk = process.env.PRIVATE_KEY;
const salt = params.CREATE2_SALT;
const networks = params.rpcUrls || [];
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('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,
quorumPercentage: params.quorumPercentage,
initialPartners: params.initialPartners,
initialAmounts: params.initialAmounts,
supportedChainIds: params.supportedChainIds
kpp: params.kpp ? BigInt(params.kpp) : 0n,
quorumPercentage: params.quorumPercentage || 51,
initialPartners: params.initialPartners || [],
initialAmounts: (params.initialAmounts || []).map(amount => BigInt(amount)),
supportedChainIds: (params.supportedChainIds || []).map(id => BigInt(id))
};
const deployTx = await DLE.getDeployTransaction(dleConfig, params.currentChainId);
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);
// DEBUG: глобальные значения
try {
const calcInitHash = ethers.keccak256(dleInit);
const saltLen = ethers.getBytes(salt).length;
console.log(`[MULTI_DBG] GLOBAL saltLenBytes=${saltLen} salt=${salt}`);
console.log(`[MULTI_DBG] GLOBAL initCodeHash(provided)=${initCodeHash}`);
console.log(`[MULTI_DBG] GLOBAL initCodeHash(calculated)=${calcInitHash}`);
console.log(`[MULTI_DBG] GLOBAL initCodeHash(calculated)=${initCodeHash}`);
console.log(`[MULTI_DBG] GLOBAL dleInit.lenBytes=${ethers.getBytes(dleInit).length} head16=${dleInit.slice(0, 34)}...`);
} catch (e) {
console.log('[MULTI_DBG] GLOBAL precheck error', e?.message || e);
}
// Подготовим провайдеры и вычислим общий nonce для фабрики
// Подготовим провайдеры и вычислим общий nonce для DLE
const providers = networks.map(u => new hre.ethers.JsonRpcProvider(u));
const wallets = providers.map(p => new hre.ethers.Wallet(pk, p));
const nonces = [];
@@ -210,15 +236,28 @@ async function main() {
const n = await providers[i].getTransactionCount(wallets[i].address, 'pending');
nonces.push(n);
}
const targetFactoryNonce = Math.max(...nonces);
console.log(`[MULTI_DBG] nonces=${JSON.stringify(nonces)} targetFactoryNonce=${targetFactoryNonce}`);
const targetDLENonce = Math.max(...nonces);
console.log(`[MULTI_DBG] nonces=${JSON.stringify(nonces)} targetDLENonce=${targetDLENonce}`);
const results = [];
for (let i = 0; i < networks.length; i++) {
const rpcUrl = networks[i];
const r = await deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetFactoryNonce, dleInit);
console.log(`[MULTI_DBG] deploying to network ${i + 1}/${networks.length}: ${rpcUrl}`);
const r = await deployInNetwork(rpcUrl, pk, salt, initCodeHash, targetDLENonce, dleInit);
results.push({ rpcUrl, ...r });
}
// Проверяем, что все адреса одинаковые
const addresses = results.map(r => r.address);
const uniqueAddresses = [...new Set(addresses)];
if (uniqueAddresses.length > 1) {
console.error('[MULTI_DBG] ERROR: DLE addresses are different across networks!');
console.error('[MULTI_DBG] addresses:', uniqueAddresses);
throw new Error('Nonce alignment failed - addresses are different');
}
console.log('[MULTI_DBG] SUCCESS: All DLE addresses are identical:', uniqueAddresses[0]);
console.log('MULTICHAIN_DEPLOY_RESULT', JSON.stringify(results));
}