Skip to content

Commit 9dd5b12

Browse files
authored
feat: add CaipAssetTypeOrId struct (#229)
This new type allows to use either a `CaipAssetType` or `CaipAssetId` without using `superstruct.union`. Resulting in better error messages.
1 parent 9ac7ec2 commit 9dd5b12

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

src/caip-types.ts

+11
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ export const CAIP_ASSET_TYPE_REGEX =
2727
export const CAIP_ASSET_ID_REGEX =
2828
/^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})\/(?<tokenId>[-.%a-zA-Z0-9]{1,78})$/u;
2929

30+
const CAIP_ASSET_TYPE_OR_ID_REGEX =
31+
/^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-_a-zA-Z0-9]{1,32}))\/(?<assetNamespace>[-a-z0-9]{3,8}):(?<assetReference>[-.%a-zA-Z0-9]{1,128})(\/(?<tokenId>[-.%a-zA-Z0-9]{1,78}))?$/u;
32+
3033
/**
3134
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
3235
*/
@@ -120,6 +123,14 @@ export const CaipAssetIdStruct =
120123
);
121124
export type CaipAssetId = Infer<typeof CaipAssetIdStruct>;
122125

126+
/**
127+
* A CAIP-19 asset type or asset ID identifier, i.e., a human-readable type of asset identifier.
128+
*/
129+
export const CaipAssetTypeOrIdStruct = definePattern<
130+
CaipAssetType | CaipAssetId
131+
>('CaipAssetTypeOrId', CAIP_ASSET_TYPE_OR_ID_REGEX);
132+
export type CaipAssetTypeOrId = Infer<typeof CaipAssetTypeOrIdStruct>;
133+
123134
/** Known CAIP namespaces. */
124135
export enum KnownCaipNamespace {
125136
/** BIP-122 (Bitcoin) compatible chains. */

src/index.test.ts

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ describe('index', () => {
2020
"CaipAssetIdStruct",
2121
"CaipAssetNamespaceStruct",
2222
"CaipAssetReferenceStruct",
23+
"CaipAssetTypeOrIdStruct",
2324
"CaipAssetTypeStruct",
2425
"CaipChainIdStruct",
2526
"CaipNamespaceStruct",

src/node.test.ts

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ describe('node', () => {
2020
"CaipAssetIdStruct",
2121
"CaipAssetNamespaceStruct",
2222
"CaipAssetReferenceStruct",
23+
"CaipAssetTypeOrIdStruct",
2324
"CaipAssetTypeStruct",
2425
"CaipChainIdStruct",
2526
"CaipNamespaceStruct",

0 commit comments

Comments
 (0)