web3.js的使用

目录

一、安装

二、使用

1.账户

2.通过助记词创建

3. 私钥、公钥和keyStore

4. 单位转换

5.转账操作


前端开发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/ 

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3中使用web3.js可以按照以下步骤进行: 1. 首先,在需要使用web3.js的页面中引入web3.js库。可以使用import语句将web3.js库导入到你的代码中。例如,可以使用以下代码导入web3.js库: ```javascript import Web3 from 'web3'; ``` 2. 接下来,你需要初始化web3实例。可以使用以下代码初始化web3实例: ```javascript const web3 = new Web3(window.ethereum); ``` 这里使用了window.ethereum作为web3的提供者,它是浏览器中的以太坊钱包提供的全局变量。 3. 然后,你可以使用web3实例来调用智能合约的方法。例如,可以使用以下代码调用智能合约的某个方法: ```javascript const contract = new web3.eth.Contract(abi, contractAddress); contract.methods.methodName().call((error, result) => { if (error) { console.error(error); } else { console.log(result); } }); ``` 这里的abi是智能合约的ABI(Application Binary Interface),contractAddress是智能合约的地址,methodName是智能合约中的某个方法名。 需要注意的是,由于web3.js的一些方法是异步的,你可能需要使用async/await或者Promise来处理异步操作。 希望以上信息对你有所帮助! #### 引用[.reference_title] - *1* *3* [在vue使用web3.js开发以太坊dapp](https://blog.csdn.net/qingshui_zhuo/article/details/112978150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [记录分享vue3通过web3.js连接MetaMask的流程及签名、验签方法](https://blog.csdn.net/q1354790820/article/details/129820494)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值