目录
一.根据 Mnemonic Word 生成密钥对 keypair
二.通过 keypair 获取 Wallet 地址 和 private key
Create Mnemonic Word
npm install bip39@3.1.0
import * as bip39 from 'bip39'
let mnemonic = bip39.generateMnemonic()
console.log(mnemonic)//Your Mnemonic Word
介绍:
一共分为两步
1.根据 Mnemonic Word 生成密钥对 keypair
2.通过 keypair 获取 Wallet 地址 和 private key
一.根据 Mnemonic Word 生成密钥对 keypair
1.将助记词转换为 seed
const Seed = await bip39.mnemonicToSeed('Your Mnemonic Word')
2.通过hdkey将seed生成HD Wallet
const hdkeyWallet = hdkey.fromMasterSeed(Seed)
3.生成钱包中在m/44'/60'/0'/0/i路径的keypair
const keypair = hdkeyWallet.derivePath("m/44'/60'/0'/0/0")
二.通过 keypair 获取 Wallet 地址 和 private key
keypair 初始化 wallet 对象
const walletObj = keypair.getWallet()
wallet 地址:getAddressString()
const walletAddress = walletObj.getAddressString()
wallet 校验地址:getChecksumAddressString()
const walletVerifyAddress = walletObj.getChecksumAddressString()
wallet PrivateKey : getPrivateKey(), 需要转换十六进制
const privateKey = walletObj.getPrivateKey().toString('hex')
代码
import * as bip39 from 'bip39'
// create Mnemonic word
let mnemonic = bip39.generateMnemonic()
console.log(mnemonic) // Mnemonic word
//一.根据MyMnemonic word生成密钥对 keypair
//将MyMnemonic word转换为 seed
const Seed = await bip39.mnemonicToSeed('Your Mnemonic word')
//通过hdkey将seed生成HD Wallet
const hdkeyWallet = hdkey.fromMasterSeed(Seed)
//生成wallet中在m/44'/60'/0'/0/i路径的keypair
const keypair = hdkeyWallet.derivePath("m/44'/60'/0'/0/0")
//二. 通过keypair 获取wallet地址和privateKey
//获取wallet对象
const walletObj = keypair.getWallet()
console.log(walletObj)
//获取wallet地址
const walletAddress = walletObj.getAddressString()
//获取wallet校验地址
const walletVerifyAddress = walletObj.getChecksumAddressString()
//获取privateKey 需要转换16进制
const privateKey = walletObj.getPrivateKey().toString('hex')
// walletAddres:wallet 地址
//privateKey : private Key