Skip to content

Commit

Permalink
Merge pull request #25 from concero/feat/clf-script-minifier
Browse files Browse the repository at this point in the history
upd minifier
  • Loading branch information
olegkron authored Nov 12, 2024
2 parents 913d038 + 01866c2 commit d28b4f4
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 97 deletions.
2 changes: 1 addition & 1 deletion packages/hardhat/contracts/ParentPoolCommon.sol
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ contract ParentPoolCommon {
uint256 internal constant LP_TOKEN_DECIMALS = 1 ether;
uint256 internal constant PRECISION_HANDLER = 10_000_000_000; // 10 ** 10
uint8 internal constant MAX_DEPOSITS_ON_THE_WAY_COUNT = 150;
// TODO: change in production
/*CHANGE-IN-PRODUCTION-TO-597_600*/
// uint256 private constant WITHDRAWAL_COOLDOWN_SECONDS = 597_600;
uint256 internal constant WITHDRAWAL_COOLDOWN_SECONDS = 60;

Expand Down
192 changes: 97 additions & 95 deletions packages/hardhat/tasks/CLFScripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,121 +3,123 @@ Replaces environment variables in a file and saves the result to a dist folder.
run with: yarn hardhat clf-build-script --path ./CLFScripts/DST.js
*/

import { task, types } from "hardhat/config";
import log, { err } from "../../utils/log";
import {task, types} from 'hardhat/config';
import log, {err} from '../../utils/log';

export const pathToScript = [__dirname, "../", "CLFScripts"];
const fs = require("fs");
const path = require("path");
export const pathToScript = [__dirname, '../', 'CLFScripts'];
const fs = require('fs');
const path = require('path');

function checkFileAccessibility(filePath) {
if (!fs.existsSync(filePath)) {
err(`The file ${filePath} does not exist.`, "checkFileAccessibility");
process.exit(1);
}
if (!fs.existsSync(filePath)) {
err(`The file ${filePath} does not exist.`, 'checkFileAccessibility');
process.exit(1);
}
}

/* replaces any strings of the form ${VAR_NAME} with the value of the environment variable VAR_NAME */
function replaceEnvironmentVariables(content) {
let missingVariable = false;
const updatedContent = content.replace(/'\${(.*?)}'/g, (match, variable) => {
const value = process.env[variable];

if (value === undefined) {
err(`Environment variable ${variable} is missing.`, "replaceEnvironmentVariables");
process.exit(1);
}
return `'${value}'`;
});

if (missingVariable) {
err("One or more environment variables are missing.", "replaceEnvironmentVariables");
process.exit(1);
}
return updatedContent;
let missingVariable = false;
const updatedContent = content.replace(/'\${(.*?)}'/g, (match, variable) => {
const value = process.env[variable];

if (value === undefined) {
err(`Environment variable ${variable} is missing.`, 'replaceEnvironmentVariables');
process.exit(1);
}
return `'${value}'`;
});

if (missingVariable) {
err('One or more environment variables are missing.', 'replaceEnvironmentVariables');
process.exit(1);
}
return updatedContent;
}

function saveProcessedFile(content, outputPath, scriptType: string) {
const outputDir = path.join(...pathToScript, `dist/${scriptType}`);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
const outputFile = path.join(outputDir, path.basename(outputPath));
fs.writeFileSync(outputFile, content, "utf8");
log(`Saved to ${outputFile}`, "saveProcessedFile");
const outputDir = path.join(...pathToScript, `dist/${scriptType}`);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
const outputFile = path.join(outputDir, path.basename(outputPath));
fs.writeFileSync(outputFile, content, 'utf8');
log(`Saved to ${outputFile}`, 'saveProcessedFile');
}

function cleanupFile(content) {
const marker = "/*BUILD_REMOVES_EVERYTHING_ABOVE_THIS_LINE*/";
const index = content.indexOf(marker);
if (index !== -1) content = content.substring(index + marker.length);
return content
.replace(/^\s*\/\/.*$/gm, "") // Remove single-line comments that might be indented
.replace(/\/\*[\s\S]*?\*\//g, "") // Remove multi-line comments
.replace(/^\s*[\r\n]/gm, ""); // Remove empty lines
const marker = '/*BUILD_REMOVES_EVERYTHING_ABOVE_THIS_LINE*/';
const index = content.indexOf(marker);
if (index !== -1) content = content.substring(index + marker.length);
return content
.replace(/^\s*\/\/.*$/gm, '') // Remove single-line comments that might be indented
.replace(/\/\*[\s\S]*?\*\//g, '') // Remove multi-line comments
.replace(/^\s*[\r\n]/gm, ''); // Remove empty lines
}

function minifyFile(content) {
return content
.replace(/\n/g, " ") // Remove newlines
.replace(/\t/g, " ") // Remove tabs
.replace(/\s\s+/g, " "); // Replace multiple spaces with a single space
return content
.replace(/\n/g, ' ') // Remove newlines
.replace(/\t/g, ' ') // Remove tabs
.replace(/\s\s+/g, ' ') // Replace multiple spaces with a single space
.replace(/;\s*/g, ';') // Remove spaces after semicolons
.replace(/\s*([=()+\-*\/{};,:<>])\s*/g, '$1'); // Remove spaces around operators
}

export function buildScript(fileToBuild: string) {
if (!fileToBuild) {
err("Path to Functions script file is required.", "buildScript");
return;
}

checkFileAccessibility(fileToBuild);

try {
let fileContent = fs.readFileSync(fileToBuild, "utf8");
fileContent = replaceEnvironmentVariables(fileContent);
let cleanedUpFile = cleanupFile(fileContent);
let minifiedFile = minifyFile(cleanedUpFile);
let scriptType = "pool";

if (fileToBuild.split("/").includes("infra")) {
scriptType = "infra";
}

saveProcessedFile(cleanedUpFile, fileToBuild, scriptType);
saveProcessedFile(minifiedFile, fileToBuild.replace(".js", ".min.js"), scriptType);
} catch (error) {
err(`Error processing file ${fileToBuild}: ${error}`, "buildScript");
process.exit(1);
}
if (!fileToBuild) {
err('Path to Functions script file is required.', 'buildScript');
return;
}

checkFileAccessibility(fileToBuild);

try {
let fileContent = fs.readFileSync(fileToBuild, 'utf8');
fileContent = replaceEnvironmentVariables(fileContent);
let cleanedUpFile = cleanupFile(fileContent);
let minifiedFile = minifyFile(cleanedUpFile);
let scriptType = 'pool';

if (fileToBuild.split('/').includes('infra')) {
scriptType = 'infra';
}

saveProcessedFile(cleanedUpFile, fileToBuild, scriptType);
saveProcessedFile(minifiedFile, fileToBuild.replace('.js', '.min.js'), scriptType);
} catch (error) {
err(`Error processing file ${fileToBuild}: ${error}`, 'buildScript');
process.exit(1);
}
}

// run with: yarn hardhat clf-script-build --file DST.js
task("clf-script-build", "Builds the JavaScript source code")
.addFlag("all", "Build all scripts")
.addOptionalParam("file", "Path to Functions script file", undefined, types.string)
.setAction(async (taskArgs, hre) => {
if (taskArgs.all) {
const paths = ["src/infra", "src/pool"];

paths.forEach((_path: string) => {
const files = fs.readdirSync(path.join(...pathToScript, _path));

files.forEach((file: string) => {
if (file.endsWith(".js")) {
const fileToBuild = path.join(...pathToScript, _path, file);
buildScript(fileToBuild);
}
});
});

return;
}
if (taskArgs.file) {
const fileToBuild = path.join(...pathToScript, "src", taskArgs.file);
buildScript(fileToBuild);
} else {
console.error("No file specified.");
process.exit(1);
}
});
task('clf-script-build', 'Builds the JavaScript source code')
.addFlag('all', 'Build all scripts')
.addOptionalParam('file', 'Path to Functions script file', undefined, types.string)
.setAction(async (taskArgs, hre) => {
if (taskArgs.all) {
const paths = ['src/infra', 'src/pool'];

paths.forEach((_path: string) => {
const files = fs.readdirSync(path.join(...pathToScript, _path));

files.forEach((file: string) => {
if (file.endsWith('.js')) {
const fileToBuild = path.join(...pathToScript, _path, file);
buildScript(fileToBuild);
}
});
});

return;
}
if (taskArgs.file) {
const fileToBuild = path.join(...pathToScript, 'src', taskArgs.file);
buildScript(fileToBuild);
} else {
console.error('No file specified.');
process.exit(1);
}
});
export default {};

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit d28b4f4

Please sign in to comment.