This repository has been archived by the owner on May 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
57 lines (48 loc) · 1.43 KB
/
index.js
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
const keccak = require('keccak')
function toChecksumAddress (address, chainId = null) {
if (typeof address !== 'string') {
return ''
}
if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
throw new Error(
`Given address "${address}" is not a valid Ethereum address.`
)
}
const stripAddress = stripHexPrefix(address).toLowerCase()
const prefix = chainId != null ? chainId.toString() + '0x' : ''
const keccakHash = keccak('keccak256')
.update(prefix + stripAddress)
.digest('hex')
let checksumAddress = '0x'
for (let i = 0; i < stripAddress.length; i++) {
checksumAddress +=
parseInt(keccakHash[i], 16) >= 8
? stripAddress[i].toUpperCase()
: stripAddress[i]
}
return checksumAddress
}
function checkAddressChecksum (address, chainId = null) {
const stripAddress = stripHexPrefix(address).toLowerCase()
const prefix = chainId != null ? chainId.toString() + '0x' : ''
const keccakHash = keccak('keccak256')
.update(prefix + stripAddress)
.digest('hex')
for (let i = 0; i < stripAddress.length; i++) {
let output =
parseInt(keccakHash[i], 16) >= 8
? stripAddress[i].toUpperCase()
: stripAddress[i]
if (stripHexPrefix(address)[i] !== output) {
return false
}
}
return true
}
function stripHexPrefix (value) {
return value.slice(0, 2) === '0x' ? value.slice(2) : value
}
module.exports = {
toChecksumAddress,
checkAddressChecksum
}