-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathisValidAddress.ts
57 lines (54 loc) · 1.51 KB
/
isValidAddress.ts
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
47
48
49
50
51
52
53
54
55
56
57
export function isValidWalletAddress(
address: string,
chainPrefix: string
): boolean {
const bech32Regex = /^[a-km-zA-HJ-NP-Z0-9]{39}$/im
if (!address?.length) {
return false
}
if (!address.startsWith(chainPrefix)) {
return false
}
const unprefixed = address.replace(chainPrefix, '')
return !!unprefixed.match(bech32Regex)
}
export function isValidValidatorAddress(
address: string,
chainPrefix: string
): boolean {
const bech32Regex = /^[a-km-zA-HJ-NP-Z0-9]{46}$/im
// Some validators may be run by DAOs and have contract addresses
// This has a length of 66 because of the valoper prefix (i.e. junovaloper)
const bech32ContractRegex = /^[a-km-zA-HJ-NP-Z0-9]{66}$/im
if (!address?.length) {
return false
}
if (address.search('valoper') < 0) {
return false
}
const unprefixed = address.replace(chainPrefix, '')
return (
!!unprefixed.match(bech32Regex) || !!unprefixed.match(bech32ContractRegex)
)
}
export function isValidContractAddress(
address: string,
chainPrefix: string
): boolean {
const bech32Regex = /^[a-km-zA-HJ-NP-Z0-9]{59}$/im
if (!address?.length) {
return false
}
if (!address.startsWith(chainPrefix)) {
return false
}
const unprefixed = address.replace(chainPrefix, '')
return !!unprefixed.match(bech32Regex)
}
// Validates a bech32 address.
export function isValidAddress(address: string, chainPrefix: string): boolean {
return (
isValidWalletAddress(address, chainPrefix) ||
isValidContractAddress(address, chainPrefix)
)
}