Описание изменений

This commit is contained in:
2025-03-19 17:18:03 +03:00
parent 04d027054d
commit 55e4d81c95
75 changed files with 2103 additions and 4861 deletions

View File

@@ -1,43 +0,0 @@
const { getContract } = require('../utils/contracts');
const logger = require('../utils/logger');
async function main() {
try {
const accessToken = await getContract('AccessToken');
const owner = await accessToken.owner();
logger.info('Contract owner:', owner);
// Проверяем все токены и их владельцев
logger.info('\nAll tokens:');
for (let i = 1; i <= 10; i++) {
try {
const tokenOwner = await accessToken.ownerOf(i);
logger.info(`Token ${i} owner: ${tokenOwner}`);
} catch (error) {
if (!error.message.includes('invalid token ID')) {
logger.error(`Token ${i} error:`, error.message);
}
}
}
// Проверяем активные токены для всех известных адресов
const addresses = [owner, '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'];
logger.info('\nActive tokens:');
for (const address of addresses) {
const activeToken = await accessToken.activeTokens(address);
logger.info(`${address}: Token ${activeToken.toString()}`);
}
} catch (error) {
logger.error(error);
process.exit(1);
}
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

View File

@@ -1,21 +0,0 @@
const { checkAllUsersTokens } = require('../utils/access-check');
const logger = require('../utils/logger');
async function main() {
logger.info('Starting token balance check for all users');
try {
await checkAllUsersTokens();
logger.info('Token balance check completed successfully');
} catch (error) {
logger.error(`Error during token balance check: ${error.message}`);
}
}
// Запуск скрипта
main()
.then(() => process.exit(0))
.catch(error => {
logger.error(`Unhandled error: ${error.message}`);
process.exit(1);
});

View File

@@ -1,29 +0,0 @@
const hre = require('hardhat');
const logger = require('../utils/logger');
async function main() {
try {
const AccessToken = await hre.ethers.getContractFactory('AccessToken');
const accessToken = await AccessToken.deploy();
await accessToken.waitForDeployment();
const address = await accessToken.getAddress();
logger.info('AccessToken deployed to:', address);
// Создаем первый админский токен для владельца контракта
const [owner] = await hre.ethers.getSigners();
const tx = await accessToken.mintAccessToken(owner.address, 1); // 1 = ADMIN
await tx.wait();
logger.info('Admin token minted for:', owner.address);
} catch (error) {
logger.error('Deployment error:', error);
process.exit(1);
}
}
main()
.then(() => process.exit(0))
.catch((error) => {
logger.error('Unhandled error:', error);
process.exit(1);
});

View File

@@ -1,22 +0,0 @@
const hre = require('hardhat');
async function main() {
console.log('Начинаем деплой контракта...');
// Получаем контракт
const MyContract = await hre.ethers.getContractFactory('MyContract');
// Деплоим контракт
const myContract = await MyContract.deploy();
await myContract.waitForDeployment();
const address = await myContract.getAddress();
console.log('Контракт развернут по адресу:', address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

View File

@@ -1,58 +0,0 @@
const hre = require('hardhat');
async function main() {
const accessToken = await hre.ethers.getContractAt(
'AccessToken',
'0xF352c498cF0857F472dC473E4Dd39551E79B1063'
);
const owner = await accessToken.owner();
console.log('Contract owner:', owner);
// Создаем админский токен для владельца
try {
const tx = await accessToken.mintAccessToken(owner, 0); // 0 = ADMIN
await tx.wait();
console.log(`Admin token minted for ${owner}`);
const role = await accessToken.checkRole(owner);
console.log('Owner role:', ['ADMIN', 'MODERATOR', 'SUPPORT'][role]);
} catch (error) {
console.log('Admin token minting error:', error.message);
}
// Создаем тестовый токен модератора
const moderatorAddress = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'; // Тестовый адрес модератора
try {
const tx = await accessToken.mintAccessToken(moderatorAddress, 1); // 1 = MODERATOR
await tx.wait();
console.log(`Moderator token minted for ${moderatorAddress}`);
const role = await accessToken.checkRole(moderatorAddress);
console.log('Moderator role:', ['ADMIN', 'MODERATOR', 'SUPPORT'][role]);
} catch (error) {
console.log('Moderator token minting error:', error.message);
}
// Проверяем все токены
console.log('\nChecking all tokens:');
for (let i = 1; i <= 5; i++) {
try {
const owner = await accessToken.ownerOf(i);
const role = await accessToken.checkRole(owner);
console.log(`Token ${i}: Owner ${owner}, Role: ${['ADMIN', 'MODERATOR', 'SUPPORT'][role]}`);
} catch (error) {
// Пропускаем несуществующие токены
if (!error.message.includes('nonexistent token')) {
console.log(`Token ${i} error:`, error.message);
}
}
}
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

View File

@@ -1,13 +1,8 @@
const { Pool } = require('pg');
const fs = require('fs');
const fs = require('fs').promises;
const path = require('path');
require('dotenv').config();
// Подключение к БД
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false,
});
const { pool } = require('../db');
const logger = require('../utils/logger');
async function runMigrations() {
try {
@@ -18,39 +13,64 @@ async function runMigrations() {
CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
applied_at TIMESTAMP DEFAULT NOW()
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Получаем список уже примененных миграций
// Получаем список выполненных миграций
const { rows } = await pool.query('SELECT name FROM migrations');
const appliedMigrations = rows.map((row) => row.name);
const executedMigrations = new Set(rows.map(row => row.name));
// Получаем список файлов миграций
const migrationsDir = path.join(__dirname, '../migrations');
const migrationFiles = fs
.readdirSync(migrationsDir)
.filter((file) => file.endsWith('.sql'))
.sort(); // Сортируем файлы по имени
// Читаем файлы миграций
const migrationsDir = path.join(__dirname, '../db/migrations');
const files = await fs.readdir(migrationsDir);
// Применяем миграции, которые еще не были применены
// Сортируем файлы по номеру
const migrationFiles = files
.filter(f => f.endsWith('.sql'))
.sort((a, b) => {
const numA = parseInt(a.split('_')[0]);
const numB = parseInt(b.split('_')[0]);
return numA - numB;
});
// Выполняем миграции
for (const file of migrationFiles) {
if (!appliedMigrations.includes(file)) {
console.log(`Применение миграции: ${file}`);
// Читаем содержимое файла миграции
if (!executedMigrations.has(file)) {
const filePath = path.join(migrationsDir, file);
const sql = fs.readFileSync(filePath, 'utf8');
const sql = await fs.readFile(filePath, 'utf-8');
// Выполняем SQL-запросы из файла
await pool.query(sql);
await pool.query('BEGIN');
try {
await pool.query(sql);
await pool.query('INSERT INTO migrations (name) VALUES ($1)', [file]);
await pool.query('COMMIT');
logger.info(`Migration ${file} executed successfully`);
} catch (error) {
await pool.query('ROLLBACK');
throw error;
}
}
}
// Записываем информацию о примененной миграции
await pool.query('INSERT INTO migrations (name) VALUES ($1)', [file]);
console.log(`Миграция ${file} успешно применена`);
} else {
console.log(`Миграция ${file} уже применена`);
// Выполняем SQL-функции
const functionsDir = path.join(migrationsDir, 'functions');
if (await fs.stat(functionsDir).then(() => true).catch(() => false)) {
const functionFiles = await fs.readdir(functionsDir);
for (const file of functionFiles) {
if (file.endsWith('.sql')) {
const filePath = path.join(functionsDir, file);
const sql = await fs.readFile(filePath, 'utf-8');
try {
await pool.query(sql);
logger.info(`Function ${file} executed successfully`);
} catch (error) {
logger.error(`Error executing function ${file}:`, error);
throw error;
}
}
}
}

View File

@@ -1,53 +0,0 @@
const { checkAllUsersTokens } = require('../utils/access-check');
const db = require('../db');
const logger = require('../utils/logger');
async function updateRolesFromOldStructure() {
try {
logger.info('Starting migration of user roles from old structure');
// Получаем пользователей со старым полем role
const usersWithOldRoles = await db.query(`
SELECT id, role, address
FROM users
WHERE role IS NOT NULL AND role_id IS NULL
`);
logger.info(`Found ${usersWithOldRoles.rows.length} users with old role structure`);
for (const user of usersWithOldRoles.rows) {
// Определяем ID роли
let roleId = 2; // По умолчанию 'user'
if (user.role === 'ADMIN' || user.role === 'admin') {
roleId = 1; // 'admin'
}
// Обновляем пользователя
await db.query(
'UPDATE users SET role_id = $1 WHERE id = $2',
[roleId, user.id]
);
logger.info(`Updated user ${user.id} with role_id ${roleId} (from old role ${user.role})`);
}
// Запускаем проверку токенов для всех пользователей
await checkAllUsersTokens();
logger.info('Role migration completed successfully');
} catch (error) {
logger.error(`Error during role migration: ${error.message}`);
}
}
// Запуск скрипта
updateRolesFromOldStructure()
.then(() => {
logger.info('Migration script completed');
process.exit(0);
})
.catch(error => {
logger.error(`Unhandled error: ${error.message}`);
process.exit(1);
});