-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathvalidateContentHash.ts
More file actions
46 lines (39 loc) · 1.47 KB
/
validateContentHash.ts
File metadata and controls
46 lines (39 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { BaseError } from '@ensdomains/ensjs'
import { encodeContentHash, getProtocolType } from '@ensdomains/ensjs/utils'
import { ContentHashProvider } from '@app/utils/contenthash'
export type ContentHashProviderOrAll = ContentHashProvider | 'all'
const contentHashToProtocols = {
ipfs: ['ipfs', 'ipns'],
swarm: ['bzz'],
onion: ['onion', 'onion3'],
skynet: ['sia'],
arweave: ['arweave', 'ar'],
walrus: ['walrus'],
}
export const validateContentHash =
(provider: ContentHashProviderOrAll) =>
(value?: string): string | boolean => {
if (!value) return true
const output = getProtocolType(value)
console.log("protocol:",output)
if (!output) return 'Invalid protocol type'
const { protocolType, decoded } = output
if (provider !== 'all' && !contentHashToProtocols[provider]?.includes(protocolType))
return 'Invalid protocol type'
if (
(['ipfs', 'bzz'].includes(protocolType) && decoded.length < 4) ||
(protocolType === 'onion' && decoded.length !== 16) ||
(protocolType === 'onion3' && decoded.length !== 56) ||
(protocolType === 'sia' && decoded.length !== 46) ||
(protocolType === 'walrus' && decoded.length !== 66) ||
(['arweave', 'ar'].includes(protocolType) && decoded.length !== 43)
)
return 'Invalid content id'
try {
encodeContentHash(value)
return true
} catch (e: unknown) {
if (e instanceof BaseError) return e.message
return 'Invalid content hash'
}
}