All files / src/services ClientService.ts

35.29% Statements 6/17
0% Branches 0/4
0% Functions 0/3
35.29% Lines 6/17

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81    1x   1x 1x 1x 1x           1x                                                                                                                                      
// SPDX-License-Identifier: Apache-2.0
 
import { Client } from '@hashgraph/sdk';
import { IService } from './IService';
import { LoggerService } from './LoggerService';
import { ServiceLocator } from './ServiceLocator';
import { CLIService } from './CLIService';
import { Errors } from '../Errors/LocalNodeErrors';
 
/**
 * Represents a service for managing the Hedera client.
 * @implements {IService}
 */
export class ClientService implements IService{
    /**
     * The logger service.
     * @private
     */
    private logger: LoggerService;
 
    /**
     * The CLI service.
     * @private
     */
    private cliService: CLIService;
 
    /**
     * The name of the service.
     * @private
     */
    private serviceName: string;
 
    /**
     * The client.
     * @private
     */
    private client: Client | undefined;
 
    /**
     * Create a client service instance.
     */
    constructor() {
        this.serviceName = ClientService.name;
        this.logger = ServiceLocator.Current.get<LoggerService>(LoggerService.name);
        this.cliService = ServiceLocator.Current.get<CLIService>(CLIService.name);
        this.logger.trace('Client Service Initialized!', this.serviceName);
    }
 
    /**
     * Sets up the client for communication with the network.
     * @throws {LocalNodeErrors} If the environment variables OPERATOR_ID and OPERATOR_KEY are not set.
     * @private
     */
    private setupClient(): void {
        Iif (process.env.RELAY_OPERATOR_ID_MAIN == null || process.env.RELAY_OPERATOR_KEY_MAIN == null) {
            throw Errors.CLEINT_ERROR("Environment variables OPERATOR_ID, and OPERATOR_KEY are required.")
        }
        const { host } = this.cliService.getCurrentArgv();
        this.client = Client.forNetwork({
            [`${host}:50211`]: '0.0.3'
          })
          .setOperator(
            process.env.RELAY_OPERATOR_ID_MAIN,
            process.env.RELAY_OPERATOR_KEY_MAIN
        );
    }
 
    /**
     * Retrieves the client instance.
     * If the client instance does not exist, it will be set up.
     * @returns {Client} The client.
     * @public
     */
    public getClient(): Client {
        Iif (!this.client) {
            this.setupClient();
        }
        return this.client as Client;
    }
}