This repository has been archived by the owner on Sep 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
index.js
84 lines (72 loc) · 2.1 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const bip39 = require('bip39')
const hdkey = require('ethereumjs-wallet/hdkey')
const Transaction = require('ethereumjs-tx')
const EthCrypto = require('eth-crypto')
const isBuffer = require('is-buffer')
class Wallet {
constructor (seed, hdpath = '') {
let value = null
if (typeof seed === 'string') {
value = Buffer.from(seed)
} else if (isBuffer(seed)) {
value = seed
} else {
throw new Error('Seed must be Buffer or string')
}
this.__hdwallet = hdkey.fromMasterSeed(value)
this.__hdpath = hdpath
}
hdpath () {
return this.__hdpath
}
getAddress () {
return this.__hdwallet.derivePath(this.__hdpath).getWallet().getAddress()
}
getPublicKey (compress = false) {
const uncompressed = this.__hdwallet.derivePath(this.__hdpath).getWallet().getPublicKey()
if (compress) {
return Buffer.from(EthCrypto.publicKey.compress(uncompressed.toString('hex')), 'hex')
}
return uncompressed
}
getPrivateKey () {
return this.__hdwallet.derivePath(this.__hdpath).getWallet().getPrivateKey()
}
signTransaction (txParams) {
const wallet = this.__hdwallet.derivePath(this.__hdpath).getWallet()
txParams.from = txParams.from || '0x' + wallet.getAddress().toString('hex')
const tx = new Transaction(txParams)
const priv = wallet.getPrivateKey()
tx.sign(priv)
return tx.serialize()
}
derive (hdpath) {
if (typeof hdpath === undefined) return this
const clone = Object.assign(Object.create(Object.getPrototypeOf(this)), this)
if (/^[0-9]+'?$/.test(hdpath)) {
hdpath = `/${hdpath}`
}
clone.__hdpath = this.__hdpath + hdpath
return clone
}
}
const HDWallet = {
fromMnemonic: (mnemonic) => {
let value = null
if (isBuffer(mnemonic)) {
value = mnemonic.toString()
} else {
value = mnemonic
}
const seed = bip39.mnemonicToSeedSync(value.trim())
return new Wallet(seed)
},
fromSeed: (seed) => {
return new Wallet(seed)
},
DefaultHDPath: 'm/44\'/60\'/0\'/0'
}
if (typeof window !== 'undefined') {
window.HDWallet = HDWallet
}
module.exports = HDWallet