-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathderive.ts
44 lines (37 loc) · 1.3 KB
/
derive.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
import HDKey from 'hdkey'
import { publicToAddress, toChecksumAddress } from '@ethereumjs/util'
export enum Derivation {
live = 'live',
legacy = 'legacy',
standard = 'standard',
testnet = 'testnet'
}
export function deriveHDAccounts(publicKey: string, chainCode: string, cb: Callback<string[]>) {
try {
const hdk = new HDKey()
hdk.publicKey = Buffer.from(publicKey, 'hex')
hdk.chainCode = Buffer.from(chainCode, 'hex')
const derive = (index: number) => {
const derivedKey = hdk.derive(`m/${index}`)
const address = Buffer.from(publicToAddress(derivedKey.publicKey, true)).toString('hex')
return toChecksumAddress(`0x${address}`)
}
const accounts = []
for (let i = 0; i < 100; i++) {
accounts[i] = derive(i)
}
cb(null, accounts)
} catch (e) {
cb(e as Error, undefined)
}
}
const derivationPaths: { [key: string]: string } = {
[Derivation.legacy.valueOf()]: "44'/60'/0'/<index>",
[Derivation.standard.valueOf()]: "44'/60'/0'/0/<index>",
[Derivation.testnet.valueOf()]: "44'/1'/0'/0/<index>",
[Derivation.live.valueOf()]: "44'/60'/<index>'/0/0"
}
export function getDerivationPath(derivation: Derivation, index = -1) {
const path = derivationPaths[derivation.valueOf()]
return path.replace('<index>', (index > -1 ? index : '').toString())
}