创建以太坊钱包

2024-05-09 16:53:49 浏览数 (3)

1 创建助记词

创建助记词我们需要用到bip39

代码语言:javascript复制
$ npm i bip39
代码语言:javascript复制
// 引入 bip39
import * as bip39 from 'bip39';
// 生成助记词
const mnemonic = bip39.generateMnemonic();
console.log('Generated mnemonic:', mnemonic);
// panda during find cart hedgehog spend pony recall plunge scatter sentence tape

2 根据助记词生成密钥对

这一步我们需要用到ethereumjs-wallet

代码语言:javascript复制
$ npm i ethereumjs-wallet
代码语言:javascript复制
import { hdkey } from 'ethereumjs-wallet';
let seed = bip39.mnemonicToSeed(mnemonic);
let hdWallet = hdkey.fromMasterSeed(seed);
let keypair = hdWallet.derivePath("m/44'/60'/0'/0/0");
console.log(keypair);

3 获取账户地址

代码语言:javascript复制
// 获取钱包
const wallet = keypair.getWallet();
console.log(wallet);

// 获取账户地址
const address = wallet.getAddressString();
console.log(address);
// 0x6858dc3a3e1c2f4de7da740bb0257ed8a0ae582b

const checkAddress = wallet.getChecksumAddressString();
console.log(checkAddress);
// 0x6858DC3A3E1c2F4de7dA740bb0257ED8A0aE582b

4 获取私钥

代码语言:javascript复制
// 获取私钥
const privateKeyString = wallet.getPrivateKeyString();
console.log(privateKeyString);
// 0x67b50b90ea53409a8df8f6d025b8d90d1ba10e9d9fe704bb255aed85691589d2

5 导出至keystore

代码语言:javascript复制
// 导出至keystore
// 1. web3.js
import { Web3 } from 'web3';
const web3 = new Web3('https://sepolia.infura.io/v3/YOUR_INFURA_ID')
const keystore = web3.eth.accounts.encrypt(privateKeyString,'111111');
console.log(keystore);
// 2. wallet对象
const v3String = await wallet.toV3('111111');
console.log(JSON.stringify(v3String));

6 从keystore导入私钥

代码语言:javascript复制
// web3.js
const privateKeyString1 = web3.eth.accounts.decrypt(keystore,'111111');
console.log(privateKeyString1)
// wallet
import ethwalletfrom 'ethereumjs-wallet';
const privateKeyString2 = await ethwallet.fromV3(v3String,'111111')
console.log(JSON.stringify(privateKeyString2));

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)[1]进行许可,使用时请注明出处。 Author: mengbin[2] blog: mengbin[3] Github: mengbin92[4] cnblogs: 恋水无意[5] 腾讯云开发者社区:孟斯特[6]

References

[1] 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0): https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh [2] mengbin: mengbin1992@outlook.com [3] mengbin: https://mengbin.top [4] mengbin92: https://mengbin92.github.io/ [5] 恋水无意: https://www.cnblogs.com/lianshuiwuyi/ [6] 孟斯特: https://cloud.tencent.com/developer/user/6649301

0 人点赞