"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 __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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.processSignOevDataRequest = exports.processHttpSignedDataRequest = exports.processHttpRequest = exports.run = exports.startCoordinator = void 0;
const path = __importStar(require("path"));
const airnode_node_1 = require("@api3/airnode-node");
const airnode_utilities_1 = require("@api3/airnode-utilities");
const promise_utils_1 = require("@api3/promise-utils");
const zod_1 = require("zod");
airnode_utilities_1.caching.init();
const configFile = path.resolve(`${__dirname}/../../config-data/config.json`);
const parsedConfig = (0, airnode_node_1.loadTrustedConfig)(configFile, process.env);
async function startCoordinator(_req, res) {
    const coordinatorId = (0, airnode_utilities_1.randomHexString)(16);
    (0, airnode_utilities_1.setLogOptions)({
        format: parsedConfig.nodeSettings.logFormat,
        level: parsedConfig.nodeSettings.logLevel,
        meta: { 'Coordinator-ID': coordinatorId },
    });
    await airnode_node_1.handlers.startCoordinator(parsedConfig, coordinatorId);
    const response = { ok: true, data: { message: 'Coordinator completed' } };
    res.status(200).send(response);
}
exports.startCoordinator = startCoordinator;
function run(req, res) {
    const payload = req.body;
    (0, airnode_utilities_1.setLogOptions)(payload.logOptions);
    switch (payload.functionName) {
        case 'initializeProvider':
            return initializeProvider(payload, res);
        case 'callApi':
            return callApi(payload, res);
        case 'processTransactions':
            return processTransactions(payload, res);
    }
}
exports.run = run;
// TODO: Refactor handlers so they are common for all the cloud providers
// https://api3dao.atlassian.net/browse/AN-527
async function initializeProvider(payload, res) {
    const { state } = payload;
    const { chainId, name: providerName } = state.settings;
    (0, airnode_utilities_1.addMetadata)({ 'Chain-ID': chainId, Provider: providerName });
    const stateWithConfig = { ...state, config: parsedConfig };
    const goInitializedState = await (0, promise_utils_1.go)(() => airnode_node_1.handlers.initializeProvider(stateWithConfig));
    if (!goInitializedState.success) {
        const msg = `Failed to initialize provider: ${stateWithConfig.settings.name}`;
        airnode_utilities_1.logger.log(goInitializedState.error.toString());
        const errorLog = airnode_utilities_1.logger.pend('ERROR', msg, goInitializedState.error);
        const body = { ok: false, errorLog };
        res.status(500).send(body);
        return;
    }
    if (!goInitializedState.data) {
        const msg = `Failed to initialize provider: ${stateWithConfig.settings.name}`;
        const errorLog = airnode_utilities_1.logger.pend('ERROR', msg);
        const body = { ok: false, errorLog };
        res.status(500).send(body);
        return;
    }
    const body = { ok: true, data: airnode_node_1.providers.scrub(goInitializedState.data) };
    res.status(200).send(body);
}
async function callApi(payload, res) {
    const { aggregatedApiCall } = payload;
    const { chainId, endpointId } = aggregatedApiCall;
    (0, airnode_utilities_1.addMetadata)({ 'Chain-ID': chainId, 'Endpoint-ID': endpointId });
    const [logs, apiCallResponse] = await airnode_node_1.handlers.callApi(parsedConfig, aggregatedApiCall);
    airnode_utilities_1.logger.logPending(logs);
    const response = { ok: true, data: apiCallResponse };
    res.status(200).send(response);
}
async function processTransactions(payload, res) {
    const { state } = payload;
    const { chainId, name: providerName } = state.settings;
    const stateWithConfig = { ...state, config: parsedConfig };
    (0, airnode_utilities_1.addMetadata)({ 'Chain-ID': chainId, Provider: providerName, 'Sponsor-Address': state.sponsorAddress });
    const goUpdatedState = await (0, promise_utils_1.go)(() => airnode_node_1.handlers.processTransactions(stateWithConfig));
    if (!goUpdatedState.success) {
        const msg = `Failed to process provider requests: ${stateWithConfig.settings.name}`;
        const errorLog = airnode_utilities_1.logger.pend('ERROR', msg, goUpdatedState.error);
        const body = { ok: false, errorLog };
        res.status(500).send(body);
        return;
    }
    const body = { ok: true, data: airnode_node_1.providers.scrub(goUpdatedState.data) };
    res.status(200).send(body);
}
// We do not want to enable ".strict()" - we want to allow extra fields in the request body
const httpRequestBodySchema = zod_1.z.object({
    parameters: zod_1.z.any(), // Parameter validation is performed later
});
async function processHttpRequest(req, res) {
    (0, airnode_utilities_1.setLogOptions)({
        format: parsedConfig.nodeSettings.logFormat,
        level: parsedConfig.nodeSettings.logLevel,
    });
    airnode_utilities_1.logger.debug(`HTTP gateway request received`);
    // Check if the request origin header is allowed in the config
    const originVerification = (0, airnode_node_1.verifyRequestOrigin)(parsedConfig.nodeSettings.httpGateway.corsOrigins, req.headers.origin);
    // Respond to preflight requests
    if (req.method === 'OPTIONS') {
        if (!originVerification.success) {
            airnode_utilities_1.logger.error(`HTTP gateway request origin verification error`);
            res.status(400).send(originVerification.error);
            return;
        }
        res.set(originVerification.headers).status(204).send('');
        return;
    }
    // Set headers for the responses
    res.set(originVerification.headers);
    airnode_utilities_1.logger.debug(`HTTP gateway request passed origin verification`);
    const parsedBody = httpRequestBodySchema.safeParse(req.body);
    if (!parsedBody.success) {
        // This error and status code is returned by AWS gateway when the request does not match the openAPI
        // specification. We want the same error to be returned by the GCP gateway.
        airnode_utilities_1.logger.error(`HTTP gateway request invalid request body`);
        res.status(400).send({ message: 'Invalid request body' });
        return;
    }
    const { parameters: rawParameters } = parsedBody.data;
    // Guaranteed to exist by the openAPI schema
    const { endpointId: rawEndpointId } = req.query;
    airnode_utilities_1.logger.debug(`HTTP gateway request passed request body parsing`);
    const verificationResult = (0, airnode_node_1.verifyHttpRequest)(parsedConfig, rawParameters, rawEndpointId);
    if (!verificationResult.success) {
        const { statusCode, error } = verificationResult;
        airnode_utilities_1.logger.error(`HTTP gateway request verification error`);
        res.status(statusCode).send(error);
        return;
    }
    const { parameters, endpointId } = verificationResult;
    (0, airnode_utilities_1.addMetadata)({ 'Endpoint-ID': endpointId });
    airnode_utilities_1.logger.debug(`HTTP gateway request passed request verification`);
    const [err, result] = await airnode_node_1.handlers.processHttpRequest(parsedConfig, endpointId, parameters);
    if (err) {
        // Returning 500 because failure here means something went wrong internally with a valid request
        airnode_utilities_1.logger.error(`HTTP gateway request processing error`);
        res.status(500).send({ message: err.toString() });
        return;
    }
    airnode_utilities_1.logger.debug(`HTTP gateway request processed successfully`);
    // We do not want the user to see {"success": true, "data": <actual_data>}, but the actual data itself
    res.status(200).send(result.data);
}
exports.processHttpRequest = processHttpRequest;
// We do not want to enable ".strict()" - we want to allow extra fields in the request body
const httpSignedDataBodySchema = zod_1.z.object({
    encodedParameters: zod_1.z.string(),
});
// TODO: Copy&paste for now, will refactor as part of
// https://api3dao.atlassian.net/browse/AN-527
async function processHttpSignedDataRequest(req, res) {
    (0, airnode_utilities_1.setLogOptions)({
        format: parsedConfig.nodeSettings.logFormat,
        level: parsedConfig.nodeSettings.logLevel,
    });
    airnode_utilities_1.logger.debug(`HTTP signed data gateway request received`);
    // Check if the request origin header is allowed in the config
    const originVerification = (0, airnode_node_1.verifyRequestOrigin)(parsedConfig.nodeSettings.httpSignedDataGateway.corsOrigins, req.headers.origin);
    // Respond to preflight requests
    if (req.method === 'OPTIONS') {
        if (!originVerification.success) {
            airnode_utilities_1.logger.error(`HTTP signed data gateway request origin verification error`);
            res.status(400).send(originVerification.error);
            return;
        }
        res.set(originVerification.headers).status(204).send('');
        return;
    }
    // Set headers for the responses
    res.set(originVerification.headers);
    airnode_utilities_1.logger.debug(`HTTP signed data gateway request passed origin verification`);
    const parsedBody = httpSignedDataBodySchema.safeParse(req.body);
    if (!parsedBody.success) {
        // This error and status code is returned by AWS gateway when the request does not match the openAPI
        // specification. We want the same error to be returned by the GCP gateway.
        airnode_utilities_1.logger.error(`HTTP signed data gateway request invalid request body`);
        res.status(400).send({ message: 'Invalid request body' });
        return;
    }
    const { encodedParameters: rawEncodedParameters } = parsedBody.data;
    // Guaranteed to exist by the openAPI schema
    const { endpointId: rawEndpointId } = req.query;
    airnode_utilities_1.logger.debug(`HTTP signed data gateway request passed request body parsing`);
    const verificationResult = (0, airnode_node_1.verifyHttpSignedDataRequest)(parsedConfig, rawEncodedParameters, rawEndpointId);
    if (!verificationResult.success) {
        const { statusCode, error } = verificationResult;
        airnode_utilities_1.logger.error(`HTTP signed data gateway request verification error`);
        res.status(statusCode).send(error);
        return;
    }
    const { encodedParameters, endpointId } = verificationResult;
    (0, airnode_utilities_1.addMetadata)({ 'Endpoint-ID': endpointId });
    airnode_utilities_1.logger.debug(`HTTP signed data gateway request passed request verification`);
    const [err, result] = await airnode_node_1.handlers.processHttpSignedDataRequest(parsedConfig, endpointId, encodedParameters);
    if (err) {
        // Returning 500 because failure here means something went wrong internally with a valid request
        airnode_utilities_1.logger.error(`HTTP signed data gateway request processing error`);
        res.status(500).send({ message: err.toString() });
        return;
    }
    airnode_utilities_1.logger.debug(`HTTP signed data gateway request processed successfully`);
    // We do not want the user to see {"success": true, "data": <actual_data>}, but the actual data itself
    res.status(200).send(result.data);
}
exports.processHttpSignedDataRequest = processHttpSignedDataRequest;
async function processSignOevDataRequest(req, res) {
    (0, airnode_utilities_1.setLogOptions)({
        format: parsedConfig.nodeSettings.logFormat,
        level: parsedConfig.nodeSettings.logLevel,
    });
    airnode_utilities_1.logger.debug(`Sign OEV data request received`);
    // Check if the request origin header is allowed in the config
    const originVerification = (0, airnode_node_1.verifyRequestOrigin)(parsedConfig.nodeSettings.oevGateway.corsOrigins, req.headers.origin);
    // Respond to preflight requests
    if (req.method === 'OPTIONS') {
        if (!originVerification.success) {
            airnode_utilities_1.logger.error(`Sign OEV data request origin verification error`);
            res.status(400).send(originVerification.error);
            return;
        }
        res.set(originVerification.headers).status(204).send('');
        return;
    }
    // Set headers for the responses
    res.set(originVerification.headers);
    airnode_utilities_1.logger.debug(`Sign OEV data request passed origin verification`);
    const parsedBody = airnode_node_1.signOevDataBodySchema.safeParse(req.body);
    if (!parsedBody.success) {
        // This error and status code is returned by AWS gateway when the request does not match the openAPI
        // specification. We want the same error to be returned by the GCP gateway.
        airnode_utilities_1.logger.error(`Sign OEV data request invalid request body`);
        res.status(400).send({ message: 'Invalid request body' });
        return;
    }
    const rawSignOevDataRequestBody = parsedBody.data;
    airnode_utilities_1.logger.debug(`HTTP signed data gateway request passed request body parsing`);
    const verificationResult = (0, airnode_node_1.verifySignOevDataRequest)(rawSignOevDataRequestBody);
    if (!verificationResult.success) {
        airnode_utilities_1.logger.error(`Sign OEV data request verification error`);
        const { statusCode, error } = verificationResult;
        res.status(statusCode).send(error);
        return;
    }
    airnode_utilities_1.logger.debug(`Sign OEV data request passed request verification`);
    const { beacons, oevUpdateHash } = verificationResult;
    const [err, result] = await airnode_node_1.handlers.signOevData(beacons, oevUpdateHash);
    if (err) {
        // Returning 500 because failure here means something went wrong internally with a valid request
        airnode_utilities_1.logger.error(`Sign OEV data request processing error`);
        res.status(500).send({ message: err.toString() });
    }
    airnode_utilities_1.logger.debug(`Sign OEV data request processed successfully`);
    // We do not want the user to see {"success": true, "data": <actual_data>}, but the actual data itself
    res.status(200).send(result.data);
}
exports.processSignOevDataRequest = processSignOevDataRequest;
//# sourceMappingURL=index.js.map