通过plasmo的wallet扩展添加新钱包

typescript 复制代码
//添加bip39库、zustand库、ethers
pnpm add bip39
pnpm add zustand
pnpm add ethers

全局状态管理zustand,管理钱包助记词和私钥:

typescript 复制代码
//新增stores\wallet.ts文件
import * as bip39 from 'bip39';
import { HDNodeWallet } from 'ethers';
import { create } from 'zustand';

interface WalletStore {
  mnemonic: string | null
  address: string | null
  wallet: HDNodeWallet | null
  setMnemonic: (mnemonic: string | null) => void
  setAddress: (address: string | null) => void
  createWallet: () => Promise<void>
}

const DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0/0"

export const useWalletStore = create<WalletStore>((set) => ({
  address: null,
  mnemonic: null,
  wallet: null,
  setMnemonic: (mnemonic) => set({ mnemonic }),
  setAddress: (address) => set({ address }),
  createWallet: async () => {
    const mnemonic = await bip39.generateMnemonic(128)
    set({ mnemonic })
    const wallet = HDNodeWallet.fromPhrase(
      mnemonic,
      "",
      DEFAULT_DERIVATION_PATH
      )
      const walletObj = {...wallet, privateKey: wallet.privateKey}
    set({ wallet: walletObj as HDNodeWallet })
  }
}))

在popup.tsx中,点击按钮即可生成新钱包,可以去小狐狸上添加验证。

typescript 复制代码
import { useWalletStore } from "~stores/wallet";

function IndexPopup() {

  const { createWallet, wallet } = useWalletStore()

  return (
    <div className="plasmo-flex plasmo-items-center plasmo-justify-center plasmo-h-16 plasmo-w-40">
      <button onClick={async () => await createWallet()}>创建钱包</button>
      <div>{JSON.stringify(wallet)}</div>
    </div>
  )
}

export default IndexPopup

一些相关理论:

typescript 复制代码
通过BIP39协议生成助记词:
1.通过generateMnemonic API 生成一段128位的二进制随机数,即Entropy(熵)。
2.对熵进行哈希运算,截取前4位,作为校验和
3.组合熵和校验和,形成132位的二进制数。
4.分成12段,每一段是11位。
5.每一段对应词库里的一个单词,最终可以形成12个单词。(如果最开始是生成256位的二进制随机数,那么就能得到24个单词)

BIP44 派生路径: m/44'/60'/0'/0/0
m:HD树的根节点,master
44':表示BIP44协议
60':当前代币类型,60代表的是以太坊
0':账户的索引,第0个账户
0:外部链/内部链,0代表外部收款地址,在链上暴露,可以用来收款。1代表内部链,不暴露,用来找零
0:钱包地址的索引
相关推荐
ALKAOUA2 小时前
力扣面试150题刷题分享
javascript·笔记
swipe2 小时前
JavaScript 对象与属性描述符:从原理到实战
前端·javascript·面试
&活在当下&2 小时前
Vue3 h函数用法详解
前端·javascript·vue.js
小贵子的博客2 小时前
(vue3错误处理)has naming conflicts with other components, ignored.
前端·javascript·vue.js
西西学代码3 小时前
Flutter---路由与导航
服务器·前端·javascript
跟着珅聪学java4 小时前
electron 安装教程
javascript·arcgis·electron
花哥码天下4 小时前
安装/卸载claude code和codex
开发语言·javascript·ecmascript
跟着珅聪学java4 小时前
Electron 读取 JSON 配置文件教程
前端·javascript·vue.js