Skip to content

Commit

Permalink
feat: add CaipAssetTypeOrId struct (#229)
Browse files Browse the repository at this point in the history
This new type allows to use either a `CaipAssetType` or `CaipAssetId`
without using `superstruct.union`. Resulting in better error messages.
  • Loading branch information
ccharly authored Jan 29, 2025
1 parent 9ac7ec2 commit 9dd5b12
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/caip-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export const CAIP_ASSET_TYPE_REGEX =
export const CAIP_ASSET_ID_REGEX =
/^(?<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;

const CAIP_ASSET_TYPE_OR_ID_REGEX =
/^(?<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;

/**
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
*/
Expand Down Expand Up @@ -120,6 +123,14 @@ export const CaipAssetIdStruct =
);
export type CaipAssetId = Infer<typeof CaipAssetIdStruct>;

/**
* A CAIP-19 asset type or asset ID identifier, i.e., a human-readable type of asset identifier.
*/
export const CaipAssetTypeOrIdStruct = definePattern<
CaipAssetType | CaipAssetId
>('CaipAssetTypeOrId', CAIP_ASSET_TYPE_OR_ID_REGEX);
export type CaipAssetTypeOrId = Infer<typeof CaipAssetTypeOrIdStruct>;

/** Known CAIP namespaces. */
export enum KnownCaipNamespace {
/** BIP-122 (Bitcoin) compatible chains. */
Expand Down
1 change: 1 addition & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('index', () => {
"CaipAssetIdStruct",
"CaipAssetNamespaceStruct",
"CaipAssetReferenceStruct",
"CaipAssetTypeOrIdStruct",
"CaipAssetTypeStruct",
"CaipChainIdStruct",
"CaipNamespaceStruct",
Expand Down
1 change: 1 addition & 0 deletions src/node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('node', () => {
"CaipAssetIdStruct",
"CaipAssetNamespaceStruct",
"CaipAssetReferenceStruct",
"CaipAssetTypeOrIdStruct",
"CaipAssetTypeStruct",
"CaipChainIdStruct",
"CaipNamespaceStruct",
Expand Down

0 comments on commit 9dd5b12

Please sign in to comment.