"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PermissionFetcher = void 0;
require("dotenv/config");
const fs = __importStar(require("fs"));
const hardhat_1 = require("hardhat");
const lodash_1 = require("lodash");
const path_1 = __importDefault(require("path"));
const typescript_retry_decorator_1 = require("typescript-retry-decorator");
const config_1 = require("./config");
const types_1 = require("./types");
class PermissionFetcher {
    constructor(network, bnbPermissionFile, chunkSize) {
        this.network = network;
        this.bnbPermissionFile = bnbPermissionFile;
        this.chunkSize = chunkSize;
        this.permissionsMap = {};
        this.missingRoleMap = {};
        this.mdFilePath = path_1.default.join(__dirname, "networks", this.network, "permissions.md");
        this.jsonFilePath = path_1.default.join(__dirname, "networks", this.network, "permissions.json");
        this.roleHashTable = this.getRoleHashTable(this.bnbPermissionFile);
        this.missingRoleFile = path_1.default.join(__dirname, "networks", this.network, "BNBMissingRole.json");
        const { permissions: existingPermissions } = this.getPermissionsJson();
        this.existingPermissions = existingPermissions;
        this.blocksParsed = parseInt(this.getPermissionsJson().height, 10);
        this.addPrevPermissionsInMap();
    }
    getPastEvents(startBlock, endBlock) {
        return __awaiter(this, void 0, void 0, function* () {
            const fromBlock = startBlock ? startBlock : config_1.startingBlockForACM[this.network];
            const toBlock = endBlock ? endBlock : yield hardhat_1.ethers.provider.getBlockNumber();
            if (fromBlock >= toBlock) {
                throw new Error(`From block ${fromBlock} cannot be more than to block ${toBlock}`);
            }
            let start = fromBlock;
            const lastStoredBlock = this.blocksParsed;
            console.log("StartBlock:", lastStoredBlock);
            if (start < lastStoredBlock) {
                start = lastStoredBlock + 1;
            }
            while (start <= toBlock) {
                const endBlock = Math.min(start + this.chunkSize - 1, toBlock);
                const events = yield this.fetchEvents(start, endBlock);
                this.processEvents(events);
                this.blocksParsed = endBlock;
                this.storeInJson();
                console.log(`Fetched events from block ${start} to ${endBlock}`);
                start = endBlock + 1;
            }
            this.updateMDPermissionFile();
        });
    }
    processEvents(events) {
        events.forEach(event => {
            const hash = this.getHash(event.contractAddress, event.functionSignature);
            if (!this.permissionsMap[hash]) {
                this.permissionsMap[hash] = {
                    contractAddress: event.contractAddress,
                    functionSignature: event.functionSignature,
                    role: hash,
                    addresses: [],
                };
            }
            const permission = this.permissionsMap[hash];
            if (event.type === types_1.PermissionsEnum.Granted) {
                permission.addresses = (0, lodash_1.union)(permission.addresses, [event.account]);
            }
            else if (event.type === types_1.PermissionsEnum.Revoked) {
                (0, lodash_1.remove)(permission.addresses, address => address === event.account);
            }
            this.permissionsMap[hash].addresses = permission.addresses;
        });
    }
    updateMDPermissionFile() {
        try {
            const jsonData = fs.readFileSync(this.jsonFilePath, "utf8");
            const data = JSON.parse(jsonData);
            let mdContent = "# Permissions\n\n";
            data.permissions.forEach((permission) => {
                mdContent += `## Contract Address: ${permission.contractAddress}\n`;
                mdContent += `- **Function Signature**: \`${permission.functionSignature}\`\n`;
                mdContent += `- **Addresses**:\n`;
                permission.addresses.forEach((address) => {
                    mdContent += `  - \`${config_1.addressMap[this.network][address] || address}\`\n`;
                });
                mdContent += "\n";
            });
            fs.writeFileSync(this.mdFilePath, mdContent, "utf8");
            console.log(`Markdown file has been written to ${this.mdFilePath}`);
        }
        catch (error) {
            console.error(`Error writing to MD file ${this.jsonFilePath}:`, error);
        }
    }
    addPrevPermissionsInMap() {
        this.existingPermissions.forEach(permission => {
            const hash = this.getHash(permission.contractAddress, permission.functionSignature);
            this.permissionsMap[hash] = permission;
        });
    }
    storeInJson() {
        const snapshot = {
            permissions: Object.values(this.permissionsMap).filter(permission => permission.addresses.length > 0),
            height: this.blocksParsed,
        };
        try {
            fs.writeFileSync(this.jsonFilePath, JSON.stringify(snapshot, null, 2), "utf8");
            console.log(`Snapshot successfully written to ${this.jsonFilePath}`);
        }
        catch (error) {
            console.error(`Error writing JSON to ${this.jsonFilePath}:`, error);
            throw new Error(`Error writing JSON to ${this.jsonFilePath}`);
        }
    }
    decodeLogs(data) {
        const abiCoder = new hardhat_1.ethers.utils.AbiCoder();
        const decodedData = abiCoder.decode(["address", "address", "string"], data);
        return { account: decodedData[0], contractAddress: decodedData[1], functionSignature: decodedData[2] };
    }
    getRoleHashTable(filePath) {
        const jsonData = fs.readFileSync(filePath, "utf8");
        const data = JSON.parse(jsonData);
        if (typeof data !== "object" || data === null || !Array.isArray(data.contracts)) {
            throw new Error("Invalid Json");
        }
        for (const contract of data.contracts) {
            if (typeof contract !== "object" || contract === null) {
                throw new Error("Invalid Json");
            }
            if (!Array.isArray(contract.address) || !Array.isArray(contract.functions)) {
                throw new Error("Invalid Json");
            }
            if (!contract.address.every((addr) => typeof addr === "string" && addr === addr.trim())) {
                throw new Error("Invalid Json");
            }
            if (!contract.functions.every((func) => typeof func === "string" && func === func.trim())) {
                throw new Error("Invalid Json");
            }
        }
        const hashTable = {};
        for (const contract of data.contracts) {
            for (const address of contract.address) {
                for (const funcSig of contract.functions) {
                    const role = this.getHash(address, funcSig);
                    hashTable[role] = {
                        contractAddress: address,
                        functionSignature: funcSig,
                    };
                }
            }
        }
        return hashTable;
    }
    fetchEvents(start, endBlock) {
        return __awaiter(this, void 0, void 0, function* () {
            const acm = yield hardhat_1.ethers.getContract("AccessControlManager");
            const acmAddress = acm.address;
            const topics = this.network === "bscmainnet"
                ? [
                    hardhat_1.ethers.utils.id("RoleGranted(bytes32,address,address)"),
                    hardhat_1.ethers.utils.id("RoleRevoked(bytes32,address,address)"),
                ]
                : [
                    hardhat_1.ethers.utils.id("PermissionGranted(address,address,string)"),
                    hardhat_1.ethers.utils.id("PermissionRevoked(address,address,string)"),
                ];
            const eventFilter = {
                acmAddress,
                topics: [topics],
            };
            const events = yield acm.queryFilter(eventFilter, start, endBlock);
            if (this.network === "bscmainnet") {
                let contractAddress;
                let functionSig;
                const newEvents = [];
                events.forEach(event => {
                    const role = hardhat_1.ethers.utils.defaultAbiCoder.decode(["bytes32"], event.topics[1])[0];
                    const account = hardhat_1.ethers.utils.defaultAbiCoder.decode(["address"], event.topics[2])[0];
                    const defaultAdminRole = "0x0000000000000000000000000000000000000000000000000000000000000000";
                    if (this.roleHashTable[role] !== undefined || role === defaultAdminRole) {
                        if (role === defaultAdminRole) {
                            contractAddress = acm.address;
                            functionSig = "DFAULT_ADMIN_ROLE";
                        }
                        else {
                            contractAddress = this.roleHashTable[role].contractAddress;
                            functionSig = this.roleHashTable[role].functionSignature;
                        }
                        const eventType = event.topics[0] === eventFilter.topics[0][0] ? types_1.PermissionsEnum.Granted : types_1.PermissionsEnum.Revoked;
                        newEvents.push({
                            contractAddress: contractAddress,
                            functionSignature: functionSig,
                            account: account,
                            type: eventType,
                        });
                    }
                    else {
                        this.addMissingRole(role, event.transactionHash);
                    }
                });
                return newEvents;
            }
            return events.map(event => {
                const data = event.data;
                const { account, contractAddress, functionSignature } = this.decodeLogs(data);
                const eventType = event.topics[0] === eventFilter.topics[0][0] ? types_1.PermissionsEnum.Granted : types_1.PermissionsEnum.Revoked;
                return {
                    contractAddress: contractAddress,
                    functionSignature: functionSignature,
                    account: account,
                    type: eventType,
                };
            });
        });
    }
    getPermissionsJson() {
        try {
            if (!fs.existsSync(this.jsonFilePath)) {
                return { permissions: [], height: config_1.startingBlockForACM[this.network].toString() };
            }
            const fileContent = fs.readFileSync(this.jsonFilePath, "utf8");
            if (!fileContent.trim()) {
                return { permissions: [], height: config_1.startingBlockForACM[this.network].toString() };
            }
            return JSON.parse(fileContent);
        }
        catch (error) {
            console.error(`Error parsing JSON file:`, error);
            throw new Error("Error parsing JSON file");
        }
    }
    addMissingRole(role, transaction) {
        let data = {};
        try {
            if (fs.existsSync(this.missingRoleFile)) {
                const fileContent = fs.readFileSync(this.missingRoleFile, "utf8").trim();
                if (fileContent) {
                    try {
                        data = JSON.parse(fileContent);
                    }
                    catch (error) {
                        console.error("Error parsing JSON:", error);
                        throw new Error("Error parsing JSON");
                    }
                }
            }
            if (!data[role]) {
                data[role] = { transactions: [] };
            }
            if (!data[role].transactions.includes(transaction)) {
                data[role].transactions.push(transaction);
            }
            fs.writeFileSync(this.missingRoleFile, JSON.stringify(data, null, 2), "utf8");
        }
        catch (error) {
            console.error("Error adding missing role:", error);
        }
    }
    getHash(contractAddress, functionSignature) {
        const hash = hardhat_1.ethers.utils.solidityKeccak256(["address", "string"], [contractAddress, functionSignature]);
        return hash;
    }
}
__decorate([
    (0, typescript_retry_decorator_1.Retryable)({
        maxAttempts: 5,
        backOffPolicy: typescript_retry_decorator_1.BackOffPolicy.ExponentialBackOffPolicy,
        backOff: 5000,
        exponentialOption: { maxInterval: 60000, multiplier: 2 },
    }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number, Number]),
    __metadata("design:returntype", Promise)
], PermissionFetcher.prototype, "fetchEvents", null);
exports.PermissionFetcher = PermissionFetcher;
//# sourceMappingURL=PermissionFetcher.js.map