"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PolymerApi = void 0;
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importDefault(require("axios"));
const logger_1 = require("../utils/logger");
const ethers_1 = require("ethers");
const flatted_1 = require("flatted");
class PolymerApi {
    config;
    constructor(config) {
        this.config = config;
    }
    async fetchProofRequest(chainId, blockNumber, txIndex, localLogIndex) {
        try {
            const proofRequest = await axios_1.default.post(this.config.guardian.polymerUrl, {
                jsonrpc: '2.0',
                id: 1,
                method: 'log_requestProof',
                params: [
                    chainId, // Source chain ID
                    blockNumber, // Block containing the event
                    txIndex, // Position of tx in block
                    localLogIndex, // Position of event in receipt
                ],
            }, {
                headers: {
                    Authorization: `Bearer ${process.env.POLYMER_API_KEY}`,
                },
            });
            return proofRequest.data;
        }
        catch (error) {
            const errMsg = error.response?.data?.error || error.message;
            logger_1.logger.error({ error: errMsg }, '🚨🧬 Polymer Could not fetch proof request');
            return null;
        }
    }
    async callExecutorAPI(srcChainId, blockNumber, logIndex, destMethod, args) {
        try {
            logger_1.logger.debug(`🧬 Polymer Calling executor API for event at block ${blockNumber}, log index ${logIndex}, on chain ${srcChainId}`);
            // Prepare the request payload
            const payload = {
                proofParams: {
                    srcChainId: srcChainId,
                    srcBlockNumber: blockNumber,
                    globalLogIndex: logIndex,
                },
                executionParams: {
                    destChainId: this.config.guardian.polymerVerifierChainId,
                    destContractAddress: this.config.guardian.polymerVerifierContractAddress,
                    method: destMethod,
                    args: args,
                    gasLimit: 500000,
                },
            };
            logger_1.logger.debug(`🧬 Polymer Sending request to ${'https://execute.testnet.polymer.zone/execute'}`);
            logger_1.logger.debug({ payload: (0, flatted_1.stringify)(payload) }, '🧬 Polymer API call payload');
            // Make the API call
            const response = await axios_1.default.post('https://execute.testnet.polymer.zone/execute', payload, {
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            if (response.data.success && response.data.result.executionResult.success) {
                logger_1.logger.debug(`✅🧬 Polymer Transaction executed: ${response.data.result.executionResult.transactionHash}`);
                logger_1.logger.debug(`⏱️🧬 Polymer Total execution time: ${response.data.result.executionTime}ms`);
                return response.data.result.executionResult.transactionHash;
            }
            else {
                logger_1.logger.error({ data: (0, flatted_1.stringify)(response.data), destMethod }, '❌🧬 Polymer Execution failed');
                return ethers_1.ethers.constants.HashZero; // Return zero hash on failure
            }
        }
        catch (error) {
            if (axios_1.default.isAxiosError(error)) {
                logger_1.logger.error({ error: (0, flatted_1.stringify)(error) }, '❌🧬 Polymer Axios Error');
                if (error.response) {
                    logger_1.logger.error({ error: error.response.status }, '❌🧬 Polymer Response status');
                }
            }
            else {
                logger_1.logger.error({ error: error instanceof Error ? error.message : String(error) }, '❌🧬 Polymer Error');
            }
            return ethers_1.ethers.constants.HashZero; // Return zero hash on failure
        }
    }
    async fetchProofRequestOrderCreated(orderId, networkConfig, maybeTxIndex, blockNumber) {
        const ORDER_CREATED_LOG_INDEX = 0;
        const chainIdHexString = networkConfig.chainId;
        // From hex to decimal
        let chainId = 0;
        let txIndex = Number.MAX_SAFE_INTEGER;
        try {
            chainId = parseInt(chainIdHexString, 16);
            if (maybeTxIndex) {
                txIndex = parseInt(maybeTxIndex);
            }
        }
        catch {
            logger_1.logger.error({ chainIdHexString }, `🧬 Polymer fetchProofRequestOrderCreated - Error parsing chainId ${chainIdHexString} to decimal`);
            return null;
        }
        if (txIndex === Number.MAX_SAFE_INTEGER) {
            logger_1.logger.debug({
                orderId,
                maybeTxIndex,
                blockNumber,
            }, '🧬 Polymer txIndex not provided orderId fetch proof order created request');
        }
        logger_1.logger.debug({
            orderId,
            networkConfig,
            txIndex,
            blockNumber,
        }, '🧬 Polymer fetching proof request for order created');
        return this.fetchProofRequest(chainId, blockNumber, txIndex, ORDER_CREATED_LOG_INDEX);
    }
}
exports.PolymerApi = PolymerApi;
//# sourceMappingURL=polymer-api.js.map