web3.js的使用

前端开发web3一共常用的库有4个,分别是:

  • web3.js [核心库]
  • ethereumjs-tx@1.3.7 (这个包已经被弃用,只有1.3.7可用,如果采用ts开发则可以使用另一个包@ethereumjs/tx) 
  • bip39 [助记词库]
  • ethereumjs-wallet [钱包库]

注意:前端开发建议使用webpack作为开发工具,使用vite会出现很多麻烦的错误。本项目使用vue-cli为例,使用的vue3版本。

一、安装

yarn add web3 ethereumjs-tx@1.3.7 bip39 ethereumjs-wallet -S
yarn add node-polyfill-webpack-plugin -D

node-polyfill-webpack-plugin库需要在vue.config.js中配置

const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')

module.exports = defineConfig({
  configureWebpack: {
    plugins: [
      new NodePolyfillPlugin(),
    ]
  }
})

二、使用

首先需要去https://app.infura.io/中去注册账户获取apikeys。

1.账户

import Web3 from 'web3'

// 实例化web3
const web3 = new Web3('https://mainnet.infura.io/ws/v3/你的apikeys')

// 创建一个账户
const account = web3.eth.accounts.create()

// 查看账户余额
web3.eth.getBalance(account.address).then(res => {
    console.log("余额是", res)
}).catch(err => {
    console.log("获取余额失败", err)
})

2.通过助记词创建

import * as bip39 from 'bip39'// 引入助记词库
import { hdkey } from 'ethereumjs-wallet'// 引入钱包库

// 创建助记词
const mnemonic = bip39.generateMnemonic()

// 生成种子
const seed = bip39.mnemonicToSeedSync(mnemonic)

// 生成hd钱包
const hdWallet = hdkey.fromMasterSeed(seed)

// 生成keypair
const keyPair = hdWallet.derivePath("m/44'/60'/0'/0/0")

// 生成钱包
const wallet = keyPair.getWallet()

// 生成私钥
const privateKey = wallet.getPrivateKey().toString('hex')

// 生成地址
const address = wallet.getAddressString()

// 生成keystore
const keyStore = await wallet.toV3(password.value)

3. 私钥、公钥和keyStore

// 私钥就是钱包。
// 公钥就是地址。
// Keystore : 私钥加密保存的json文件,必须配合钱包密码一起使用。
// 私钥=助记词,助记词可以关联多个私钥,但是私钥不可获取助记词。

import EthWallet from 'ethereumjs-wallet'

// 通过 keyStore 获取私钥
// 方法1:webjs
const privateKey1 = web3.eth.accounts.decrypt(keyStore, "钱包密码")
// 方法2:wallet对象
EthWallet.fromV3(keyStore, "钱包密码", (err, wallet) => {
    if (!err) {
      console.log("privateKey1", wallet.getPrivateKey().toString("hex"))
    }
})

// 通过私钥获取地址
const prKey2 = Buffer(privateKey, "hex")
const wallet1 = EthWallet.fromPrivateKey(prKey2)
const lowerCaseAddress1 = wallet1.getAddressString()

4. 单位转换

// Eth转wei
const num = Web3.utils.toWei("0.3")

// wei转Eth
const num = Web3.utils.fromWei("1000000000000000000", "ether")

5.转账操作

import Tx from 'ethereumjs-tx'

// 获取账户的交易次数
const nonce = await web3.eth.getTransactionCount(account.address)

// 获取转账的 gas 费
const gasPrice = await web3.eth.getGasPrice()

// 金额 Eth 转 wei
const value = web3.utils.toWei("交易金额")

 // 构建交易对象
const rawTx = {
    form: account.address,
    to: "接收地址",
    nonce,
    gasPrice,
    value,
    data: "0x0000"
}

// 转化私钥
const privateKey = Buffer(account.privateKey.slice(2), "hex")

// gas 估算
const gas = await web3.eth.estimateGas(rawTx)
rawTx.gas = gas

// 私钥加密
const tx = new Tx(rawTx)
tx.sign(privateKey)

// 生成 serializedTx
const serializedTx = "0x" + tx.serialize().toString("hex")

// 发送交易
const trans = web3.eth.sendSignedTransaction(serializedTx)

trans.on("transactionHash", txid => {
    console.log("交易id", txid)
    console.log(`https://goerli.etherscan.io/tx/${txid}`)
})

// 第一个节点确认
trans.on("receipt", receipt => {
    console.log("交易回执", receipt)
})

// 每个节点确认
trans.on("confirmation", (confirmationNumber, receipt) => {
    console.log("交易确认次数", confirmationNumber)
    console.log("交易回执", receipt)
})

trans.on("error", err => {
    console.log("交易失败", err)
})

掌握以上的方法,前端基本还是可以够用的,如果需要更加详细的文档,可以参考https://learnblockchain.cn/docs/web3.js/ 

相关推荐

  1. web3.js使用

    2024-05-13 08:52:03       35 阅读
  2. 使用intro.js实现web页面引导页

    2024-05-13 08:52:03       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-13 08:52:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-13 08:52:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-13 08:52:03       82 阅读
  4. Python语言-面向对象

    2024-05-13 08:52:03       91 阅读

热门阅读

  1. 历史文件清理

    2024-05-13 08:52:03       30 阅读
  2. 记一次requests.get()返回数据乱码问题

    2024-05-13 08:52:03       32 阅读
  3. Sass详解

    2024-05-13 08:52:03       34 阅读
  4. 如何加密Oracle后台存储过程

    2024-05-13 08:52:03       30 阅读
  5. Windows环境docker安装MySQL挂载配置不生效问题处理

    2024-05-13 08:52:03       30 阅读
  6. react组件渲染优化-类组件渲染优化

    2024-05-13 08:52:03       44 阅读
  7. vue3 <script setup> 形式父子组件传值

    2024-05-13 08:52:03       26 阅读
  8. 文心一言指令

    2024-05-13 08:52:03       35 阅读