All files / src/TxSubmit TxSubmitHttpService.ts

87.5% Statements 21/24
83.33% Branches 5/6
100% Functions 2/2
87.5% Lines 21/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 5935x             35x   35x 35x 35x 35x             35x         7x   7x 7x     5x 5x   3x 3x       3x 3x       3x     3x 1x   2x 2x                
import {
  CardanoNodeUtil,
  ProviderError,
  ProviderFailure,
  TxSubmitProvider,
  providerFailureToStatusCodeMap
} from '@cardano-sdk/core';
import { HttpServer, HttpService } from '../Http';
import { Logger } from 'ts-log';
import { ServiceNames } from '../Program/programs/types';
import { providerHandler } from '../util';
import bodyParser from 'body-parser';
import express from 'express';
 
export interface TxSubmitHttpServiceDependencies {
  logger: Logger;
  txSubmitProvider: TxSubmitProvider;
}
 
export class TxSubmitHttpService extends HttpService {
  constructor(
    { logger, txSubmitProvider }: TxSubmitHttpServiceDependencies,
    router: express.Router = express.Router()
  ) {
    super(ServiceNames.TxSubmit, txSubmitProvider, router, __dirname, logger);
 
    router.use(bodyParser.raw());
    router.post(
      '/submit',
      providerHandler(txSubmitProvider.submitTx.bind(txSubmitProvider))(async (_, _r, res, _n, handler) => {
        try {
          return HttpServer.sendJSON(res, await handler(_r.body));
        } catch (error) {
          logger.error(error);
          const firstError = Array.isArray(error) ? error[0] : error;
          // TODO: once all providers implement Provider,
          // move this check to a base class method
          let isHealthy;
          try {
            isHealthy = (await txSubmitProvider.healthCheck()).ok;
          } catch {
            isHealthy = false;
          }
          Iif (CardanoNodeUtil.isProviderError(error)) {
            return HttpServer.sendJSON(res, error, providerFailureToStatusCodeMap[error.reason]);
          }
          if (!isHealthy) {
            return HttpServer.sendJSON(res, new ProviderError(ProviderFailure.Unhealthy, firstError), 503);
          }
          if (CardanoNodeUtil.asTxSubmissionError(error)) {
            return HttpServer.sendJSON(res, new ProviderError(ProviderFailure.BadRequest, firstError), 400);
          }
          return HttpServer.sendJSON(res, new ProviderError(ProviderFailure.Unknown, firstError), 500);
        }
      }, logger)
    );
  }
}