Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Resolve Type Warnings for ConfigService.get() #3350

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
32 changes: 29 additions & 3 deletions packages/config-service/src/services/globalConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,30 @@
*
*/

type TypeStrToType<Tstr extends string> = Tstr extends 'string'
? string
: Tstr extends 'boolean'
? boolean
: Tstr extends 'number'
? number
: Tstr extends 'array'
? unknown[]
: never;

type GetTypeStrOfKey<K extends string> = K extends keyof typeof _CONFIG
? typeof _CONFIG[K]['type']
: never;

export type TypeOfKey<K extends string> = TypeStrToType<GetTypeStrOfKey<K>>;

export interface ConfigProperty {
envName: string;
type: string;
required: boolean;
defaultValue: string | number | boolean | null;
}

export class GlobalConfig {
public static readonly ENTRIES: Record<string, ConfigProperty> = {
const _CONFIG = {
BATCH_REQUESTS_ENABLED: {
envName: 'BATCH_REQUESTS_ENABLED',
type: 'boolean',
Expand Down Expand Up @@ -568,6 +583,12 @@ export class GlobalConfig {
required: false,
defaultValue: null,
},
SERVER_HOST: {
envName: 'SERVER_HOST',
type: 'string',
required: false,
defaultValue: null,
},
SERVER_PORT: {
envName: 'SERVER_PORT',
type: 'number',
Expand Down Expand Up @@ -742,5 +763,10 @@ export class GlobalConfig {
required: false,
defaultValue: null,
},
};
} as const satisfies { [key: string]: ConfigProperty };

export type ConfigKey = keyof typeof _CONFIG;

export class GlobalConfig {
public static readonly ENTRIES: Record<ConfigKey, ConfigProperty> = _CONFIG;
}
5 changes: 3 additions & 2 deletions packages/config-service/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import dotenv from 'dotenv';
import findConfig from 'find-config';
import pino from 'pino';

import type { ConfigKey, TypeOfKey } from './globalConfig';
import { LoggerService } from './loggerService';
import { ValidationService } from './validationService';

Expand Down Expand Up @@ -97,7 +98,7 @@ export class ConfigService {
* @param name string
* @returns string | undefined
*/
public static get(name: string): string | number | boolean | null | undefined {
return this.getInstance().envs[name];
public static get<K extends ConfigKey>(name: K): TypeOfKey<K> | undefined {
return this.getInstance().envs[name] as TypeOfKey<K> | undefined;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
*
* Hedera JSON RPC Relay
*
* Copyright (C) 2024 Hedera Hashgraph, LLC
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -21,6 +21,7 @@
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { ConfigService } from '../../../src/services';
import type { ConfigKey } from '../../../src/services/globalConfig';

chai.use(chaiAsPromised);

Expand Down Expand Up @@ -55,7 +56,7 @@ describe('ConfigService tests', async function () {
});

it('should return undefined for non-existing variable', async () => {
const res = ConfigService.get('NON_EXISTING_VAR');
const res = ConfigService.get('NON_EXISTING_VAR' as ConfigKey);
acuarica marked this conversation as resolved.
Show resolved Hide resolved

expect(res).to.equal(undefined);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('LoggerService tests', async function () {
});

it('should be able to return plain information', async () => {
const envName = GlobalConfig.ENTRIES.CHAIN_ID.envName;
const envName = 'CHAIN_ID';
const res = ConfigService.get(envName);

expect(LoggerService.maskUpEnv(envName, res)).to.equal(`${envName} = ${res}`);
Expand Down
5 changes: 3 additions & 2 deletions packages/relay/tests/lib/eth/eth-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
*/

import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';

import { nanOrNumberTo0x,numberTo0x } from '../../../dist/formatters';
import constants from '../../../src/lib/constants';
import {
defaultDetailedContractResultByHash,
defaultEvmAddress,
Expand All @@ -29,8 +32,6 @@ import {
mockData,
toHex,
} from '../../helpers';
import { numberTo0x, nanOrNumberTo0x } from '../../../dist/formatters';
import constants from '../../../src/lib/constants';

export const BLOCK_TRANSACTION_COUNT = 77;
export const GAS_USED_1 = 200000;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ describe('@ethSendRawTransaction eth_sendRawTransaction spec', async function ()
},
receiver_sig_required: false,
};
const useAsyncTxProcessing = ConfigService.get('USE_ASYNC_TX_PROCESSING') as boolean;
const useAsyncTxProcessing = ConfigService.get('USE_ASYNC_TX_PROCESSING');

beforeEach(() => {
clock = useFakeTimers();
Expand Down
7 changes: 7 additions & 0 deletions packages/relay/tests/lib/hapiService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ describe('HAPI Service', async function () {
const hapiClientTransactionReset = Number(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET'));

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);

expect(hapiService.getTransactionCount()).to.eq(hapiClientTransactionReset);

const oldClientInstance = hapiService.getMainClientInstance();
Expand All @@ -107,6 +108,7 @@ describe('HAPI Service', async function () {
const hapiClientDurationReset = Number(ConfigService.get('HAPI_CLIENT_DURATION_RESET'));

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);

expect(hapiService.getTimeUntilReset()).to.be.approximately(hapiClientDurationReset, 10); // 10 ms tolerance

const oldClientInstance = hapiService.getMainClientInstance();
Expand All @@ -116,6 +118,7 @@ describe('HAPI Service', async function () {
const newClientInstance = hapiService.getMainClientInstance();

expect(hapiService.getTimeUntilReset()).to.be.approximately(hapiClientDurationReset, 10); // 10 ms tolerance

expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);
});
Expand All @@ -126,6 +129,7 @@ describe('HAPI Service', async function () {
const hapiClientErrorReset: Array<number> = JSON.parse(ConfigService.get('HAPI_CLIENT_ERROR_RESET') as string);

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);

expect(hapiService.getErrorCodes()[0]).to.eq(hapiClientErrorReset[0]);

const oldClientInstance = hapiService.getMainClientInstance();
Expand All @@ -136,6 +140,7 @@ describe('HAPI Service', async function () {

expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);

expect(hapiService.getErrorCodes()[0]).to.eq(hapiClientErrorReset[0]);
});
});
Expand All @@ -161,6 +166,7 @@ describe('HAPI Service', async function () {

expect(hapiService.getTimeUntilReset()).to.be.approximately(hapiClientDurationReset, 10); // 10 ms tolerance
expect(hapiService.getTransactionCount()).to.eq(hapiClientTransactionReset - 1); // one less because we took the instance once and decreased the counter

expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);
});
Expand Down Expand Up @@ -207,6 +213,7 @@ describe('HAPI Service', async function () {
() => {
it('should not be able to reinitialise and decrement counters, if it is disabled', async function () {
hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);

expect(hapiService.getTransactionCount()).to.eq(Number(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET')));

const oldClientInstance = hapiService.getMainClientInstance();
Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/mirrorNodeClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ describe('MirrorNodeClient', async function () {
withOverriddenEnvsInMochaTest({ MIRROR_NODE_URL_HEADER_X_API_KEY: 'abc123iAManAPIkey' }, () => {
it('Can provide custom x-api-key header', async () => {
const mirrorNodeInstanceOverridden = new MirrorNodeClient(
ConfigService.get('MIRROR_NODE_URL') || '',
(ConfigService.get('MIRROR_NODE_URL')) || '',
logger.child({ name: `mirror-node` }),
registry,
cacheService,
Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/net.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('Net', async function () {
});

it('should execute "net_version"', function () {
const hederaNetwork: string = (ConfigService.get('HEDERA_NETWORK') || '{}').toLowerCase();
const hederaNetwork: string = ((ConfigService.get('HEDERA_NETWORK')) || '{}').toLowerCase();
let expectedNetVersion = ConfigService.get('CHAIN_ID') || constants.CHAIN_IDS[hederaNetwork] || '298';
if (expectedNetVersion.startsWith('0x')) expectedNetVersion = parseInt(expectedNetVersion, 16).toString();

Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/openrpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe('Open RPC Specification', function () {
const cacheService = new CacheService(logger.child({ name: `cache` }), registry);
// @ts-ignore
mirrorNodeInstance = new MirrorNodeClient(
ConfigService.get('MIRROR_NODE_URL') || '',
(ConfigService.get('MIRROR_NODE_URL')) || '',
logger.child({ name: `mirror-node` }),
registry,
cacheService,
Expand Down
11 changes: 7 additions & 4 deletions packages/relay/tests/lib/poller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@
*/

import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';
import { EthImpl } from '../../src/lib/eth';
import { expect } from 'chai';
import pino from 'pino';
import { Poller } from '../../src/lib/poller';
import sinon from 'sinon';
import { Registry } from 'prom-client';
import sinon from 'sinon';

import { EthImpl } from '../../src/lib/eth';
import { Poller } from '../../src/lib/poller';

const logger = pino({ level: 'trace' });

Expand Down Expand Up @@ -187,7 +188,9 @@ describe('Polling', async function () {
),
).to.equal(true);
expect(
loggerSpy.calledWith(`Poller: Starting polling with interval=${ConfigService.get('WS_POLLING_INTERVAL')}`),
loggerSpy.calledWith(
`Poller: Starting polling with interval=${ConfigService.get('WS_POLLING_INTERVAL')}`,
),
).to.equal(true);
});

Expand Down
4 changes: 2 additions & 2 deletions packages/relay/tests/lib/sdkClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ describe('SdkClient', async function () {

// mirror node client
mirrorNodeClient = new MirrorNodeClient(
ConfigService.get('MIRROR_NODE_URL') || '',
(ConfigService.get('MIRROR_NODE_URL')) || '',
logger.child({ name: `mirror-node` }),
registry,
new CacheService(logger.child({ name: `cache` }), registry),
Expand Down Expand Up @@ -2743,7 +2743,7 @@ describe('SdkClient', async function () {
});

it('Should execute getTransferAmountSumForAccount() to calculate transactionFee by only transfers that are paid by the specify accountId', () => {
const accountId = ConfigService.get('OPERATOR_ID_MAIN') || '';
const accountId = (ConfigService.get('OPERATOR_ID_MAIN')) || '';
const mockedTxRecord = getMockedTransactionRecord(EthereumTransaction.name, true);

const transactionFee = sdkClient.getTransferAmountSumForAccount(mockedTxRecord, accountId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ describe('HBAR Rate Limit Service', function () {
const mockPlanId = uuidV4(randomBytes(16));
const todayAtMidnight = new Date().setHours(0, 0, 0, 0);

const operatorAddress = prepend0x(
AccountId.fromString(ConfigService.get('OPERATOR_ID_MAIN')).toSolidityAddress(),
);

const requestDetails = new RequestDetails({ requestId: '', ipAddress: mockIpAddress });

let cacheService: CacheService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,15 @@ describe('Metric Service', function () {

before(() => {
// consensus node client
const hederaNetwork = ConfigService.get('HEDERA_NETWORK')! as string;
const hederaNetwork = ConfigService.get('HEDERA_NETWORK')!;
if (hederaNetwork in constants.CHAIN_IDS) {
client = Client.forName(hederaNetwork);
} else {
client = Client.forNetwork(JSON.parse(hederaNetwork));
}
client = client.setOperator(
AccountId.fromString(ConfigService.get('OPERATOR_ID_MAIN')! as string),
Utils.createPrivateKeyBasedOnFormat(ConfigService.get('OPERATOR_KEY_MAIN')! as string),
AccountId.fromString(ConfigService.get('OPERATOR_ID_MAIN')!),
Utils.createPrivateKeyBasedOnFormat(ConfigService.get('OPERATOR_KEY_MAIN')!),
);

// mirror node client
Expand All @@ -165,7 +165,7 @@ describe('Metric Service', function () {
timeout: 20 * 1000,
});
mirrorNodeClient = new MirrorNodeClient(
(ConfigService.get('MIRROR_NODE_URL') as string) || '',
(ConfigService.get('MIRROR_NODE_URL')) || '',
logger.child({ name: `mirror-node` }),
registry,
new CacheService(logger.child({ name: `cache` }), registry),
Expand Down
2 changes: 1 addition & 1 deletion packages/server/tests/acceptance/conformityTests.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*-
*
* Hedera JSON RPC Relay
*
Expand Down
8 changes: 5 additions & 3 deletions packages/server/tests/acceptance/hbarLimiter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ describe('@hbarlimiter HBAR Limiter Acceptance Tests', function () {
metrics: MetricsClient;
relayIsLocal: boolean;
} = global;

const mockTTL = ConfigService.get('HBAR_RATE_LIMIT_DURATION') as number; // 1 day
const operatorAccount = ConfigService.get('OPERATOR_ID_MAIN') as string;

const fileAppendChunkSize = Number(ConfigService.get('FILE_APPEND_CHUNK_SIZE')) || 5120;
const requestId = 'hbarLimiterTest';
const requestDetails = new RequestDetails({ requestId: requestId, ipAddress: '0.0.0.0' });
Expand Down Expand Up @@ -126,7 +128,7 @@ describe('@hbarlimiter HBAR Limiter Acceptance Tests', function () {

return contract;
};
const transactionReecordCostTolerance = Number(ConfigService.get(`TEST_TRANSACTION_RECORD_COST_TOLERANCE`) || 0.02);
const transactionReecordCostTolerance = Number(ConfigService.get('TEST_TRANSACTION_RECORD_COST_TOLERANCE') || 0.02);

const verifyRemainingLimit = (expectedCost: number, remainingHbarsBefore: number, remainingHbarsAfter: number) => {
const delta = transactionReecordCostTolerance * expectedCost;
Expand Down Expand Up @@ -738,7 +740,7 @@ describe('@hbarlimiter HBAR Limiter Acceptance Tests', function () {
};

describe('given a valid JSON file with pre-configured spending plans', async () => {
const SPENDING_PLANS_CONFIG_FILE = ConfigService.get('HBAR_SPENDING_PLANS_CONFIG') as string;
const SPENDING_PLANS_CONFIG_FILE = ConfigService.get('HBAR_SPENDING_PLANS_CONFIG');
const configPath = findConfig(SPENDING_PLANS_CONFIG_FILE);

if (configPath) {
Expand Down Expand Up @@ -898,7 +900,7 @@ describe('@hbarlimiter HBAR Limiter Acceptance Tests', function () {
return { ...aliasAccount, hbarSpendingPlan: accountAliasPlan.hbarSpendingPlan };
});

const totalHbarBudget = ConfigService.get(`HBAR_RATE_LIMIT_TINYBAR`) as number;
const totalHbarBudget = ConfigService.get('HBAR_RATE_LIMIT_TINYBAR');

let totalHbarSpent =
totalHbarBudget - Number(await metrics.get(testConstants.METRICS.REMAINING_HBAR_LIMIT));
Expand Down
1 change: 1 addition & 0 deletions packages/server/tests/acceptance/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*
*/

// Important! Load env variables before importing anything else
// Important! Load env variables before importing anything else
import dotenv from 'dotenv';
import path from 'path';
Expand Down
11 changes: 6 additions & 5 deletions packages/server/tests/acceptance/rateLimiter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@

// Assertions and constants from local resources

import Assertions from '../helpers/assertions';
import testConstants from '../../tests/helpers/constants';
import relayConstants from '@hashgraph/json-rpc-relay/dist/lib/constants';
import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';
import relayConstants from '@hashgraph/json-rpc-relay/dist/lib/constants';

import testConstants from '../../tests/helpers/constants';
import RelayClient from '../clients/relayClient';
import Assertions from '../helpers/assertions';

describe('@ratelimiter Rate Limiters Acceptance Tests', function () {
this.timeout(480 * 1000); // 480 seconds
Expand All @@ -36,9 +37,9 @@ describe('@ratelimiter Rate Limiters Acceptance Tests', function () {
let requestId: string;

const TIER_2_RATE_LIMIT =
(ConfigService.get('TIER_2_RATE_LIMIT') as unknown as number) || relayConstants.DEFAULT_RATE_LIMIT.TIER_2;
(ConfigService.get('TIER_2_RATE_LIMIT')) || relayConstants.DEFAULT_RATE_LIMIT.TIER_2;
const LIMIT_DURATION =
(ConfigService.get('LIMIT_DURATION') as unknown as number) || relayConstants.DEFAULT_RATE_LIMIT.DURATION;
(ConfigService.get('LIMIT_DURATION')) || relayConstants.DEFAULT_RATE_LIMIT.DURATION;

describe('RPC Rate Limiter Acceptance Tests', () => {
const sendMultipleRequests = async (method: string, params: any[], threshold: number) => {
Expand Down
Loading
Loading