From 9d2dd2547458db75c4ef5642a13ff1a5b81f4371 Mon Sep 17 00:00:00 2001 From: Felipe Mendes Date: Fri, 13 Dec 2024 14:55:49 -0300 Subject: [PATCH] feat: add caip address parsing utils --- packages/core/src/utils/CoreHelperUtil.ts | 31 +++++++++++++++++ .../core/tests/utils/CoreHelperUtil.test.ts | 33 +++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/packages/core/src/utils/CoreHelperUtil.ts b/packages/core/src/utils/CoreHelperUtil.ts index 1034800e25..97293a8061 100644 --- a/packages/core/src/utils/CoreHelperUtil.ts +++ b/packages/core/src/utils/CoreHelperUtil.ts @@ -357,5 +357,36 @@ export const CoreHelperUtil = { address, type } as AccountTypeMap[N] + }, + + isCaipAddress(address?: unknown): address is CaipAddress { + if (typeof address !== 'string') { + return false + } + + const sections = address.split(':') + const namespace = sections[0] + + return sections.length === 3 && (namespace as string) in CommonConstants.CHAIN_NAME_MAP + }, + + parseCaipAddress( + caipAddress?: unknown + ): { chainNamespace: ChainNamespace; chainId: string; address: string } | undefined { + if (CoreHelperUtil.isCaipAddress(caipAddress)) { + const [chainNamespace, chainId, address] = caipAddress.split(':') as [ + ChainNamespace, + string, + string + ] + + return { + chainNamespace, + chainId, + address + } + } + + return undefined } } diff --git a/packages/core/tests/utils/CoreHelperUtil.test.ts b/packages/core/tests/utils/CoreHelperUtil.test.ts index b3f4c69112..1c88058805 100644 --- a/packages/core/tests/utils/CoreHelperUtil.test.ts +++ b/packages/core/tests/utils/CoreHelperUtil.test.ts @@ -57,4 +57,37 @@ describe('CoreHelperUtil', () => { global.window.self = originalSelf } }) + + it.each([ + [undefined, false], + [{}, false], + ['0x0', false], + ['invalid_namespace:mock_chain_id:address', false], + ['eip155:mock_chain_id:mock_address', true], + ['solana:mock_chain_id:mock_address', true], + ['bip122:mock_chain_id:mock_address', true] + ])('should validate the value $s is valid caip address $b', (caipAddress, expected) => { + expect(CoreHelperUtil.isCaipAddress(caipAddress)).toEqual(expected) + }) + + it.each([ + [undefined, undefined], + [{}, undefined], + ['0x0', undefined], + ['invalid_namespace:mock_chain_id:address', undefined], + [ + 'eip155:mock_chain_id:mock_address', + { chainNamespace: 'eip155', chainId: 'mock_chain_id', address: 'mock_address' } + ], + [ + 'solana:mock_chain_id:mock_address', + { chainNamespace: 'solana', chainId: 'mock_chain_id', address: 'mock_address' } + ], + [ + 'bip122:mock_chain_id:mock_address', + { chainNamespace: 'bip122', chainId: 'mock_chain_id', address: 'mock_address' } + ] + ])('should validate the value $s is valid caip address $b', (caipAddress, expected) => { + expect(CoreHelperUtil.parseCaipAddress(caipAddress)).toEqual(expected) + }) })