diff --git a/__tests__/network/utils.test.ts b/__tests__/network/utils.test.ts new file mode 100644 index 0000000..ca00c5f --- /dev/null +++ b/__tests__/network/utils.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'bun:test' +import { NetworkId } from 'src/network/constants' +import { isAlgodConfig, isNetworkConfigMap, isValidNetworkId } from 'src/network/utils' + +describe('Type Guards', () => { + describe('isValidNetworkId', () => { + it('returns true for a valid NetworkId', () => { + expect(isValidNetworkId(NetworkId.TESTNET)).toBe(true) + }) + + it('returns false for an invalid NetworkId', () => { + expect(isValidNetworkId('foo')).toBe(false) + }) + }) + + describe('isAlgodConfig', () => { + it('returns true for a valid AlgodConfig', () => { + expect( + isAlgodConfig({ + token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + baseServer: 'http://localhost', + port: 1234, + headers: { + 'X-Foo': 'bar' + } + }) + ).toBe(true) + + expect( + isAlgodConfig({ + token: '', + baseServer: '' + }) + ).toBe(true) + }) + + it('returns false for an invalid AlgodConfig', () => { + expect( + isAlgodConfig({ + baseServer: '' + }) + ).toBe(false) + + expect( + isAlgodConfig({ + token: '' + }) + ).toBe(false) + + expect( + isAlgodConfig({ + token: '', + baseServer: '', + foo: '' + }) + ).toBe(false) + }) + }) + + describe('isNetworkConfigMap', () => { + it('returns true for a valid NetworkConfigMap', () => { + const validConfigMap = { + [NetworkId.MAINNET]: { + token: '', + baseServer: '' + }, + [NetworkId.TESTNET]: { + token: '', + baseServer: '' + } + } + expect(isNetworkConfigMap(validConfigMap)).toBe(true) + }) + + it('returns false for an invalid NetworkConfigMap', () => { + expect( + isNetworkConfigMap({ + token: '', + baseServer: '' + }) + ).toBe(false) + }) + }) +}) diff --git a/src/network/utils.ts b/src/network/utils.ts index b770aaa..e9072eb 100644 --- a/src/network/utils.ts +++ b/src/network/utils.ts @@ -5,6 +5,21 @@ export function isValidNetworkId(networkId: any): networkId is NetworkId { return Object.values(NetworkId).includes(networkId) } +export function isAlgodConfig(config: any): config is AlgodConfig { + if (typeof config !== 'object') return false + + for (const key of Object.keys(config)) { + if (!['token', 'baseServer', 'port', 'headers'].includes(key)) return false + } + + return ( + typeof config.token === 'string' && + typeof config.baseServer === 'string' && + ['string', 'number', 'undefined'].includes(typeof config.port) && + ['object', 'undefined'].includes(typeof config.headers) + ) +} + export function isNetworkConfigMap(config: NetworkConfig): config is NetworkConfigMap { const networkKeys = Object.values(NetworkId) as string[] return Object.keys(config).some((key) => networkKeys.includes(key))