Web3js 小笔记
Posted Web3js 中文学习社区
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web3js 小笔记相关的知识,希望对你有一定的参考价值。
Web3js
区块链是一个由区块组成的列表,这些块的内容基本是交易记录,每个交易都有一个附加的交易日志,事件结果存放在交易日志里。合约发出的时间,可以使用合约地址访问
基本使用
入门认知
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
console.log(web3)
查看 web3 连接的节点信息
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
web3.eth.getNodeInfo().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JFIpjIPd-1643027019279)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642950429162.png)]
查看是否连接到节点
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
web3.eth.net.isListening().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gKiGPoBY-1643027019280)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642950545009.png)]
获取当前连接网络的 id
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
web3.eth.net.getId().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0TO6aeDn-1643027019282)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642950737493.png)]
Provider 相关
查看当前 web3 provider
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
console.log(web3.currentProvider)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hjCu6Bve-1643027019282)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642951277107.png)]
设置/修改 provider
其实就是临时修改为其他的 provider
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
web3.setProvider(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
批处理
批处理请求就是将几个请求打包在一起提交
可以保证交易顺序
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
var abi = [
"inputs": [],
"name": "getNumber",
"outputs": [
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "uint256",
"name": "_number",
"type": "uint256"
],
"name": "setNumber",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
]
var address = "0x28A6FDdD4925386A5b5D8e339dF9A073fE8e74A4"
var contract = new web3.eth.Contract(abi, address)
function callback1()
console.log("callback run 1")
function callback2()
console.log("callback run 2")
// 创建批处理对象
var batch = new web3.BatchRequest()
// 添加事务
batch.add(web3.eth.getBalance.request('0x9EC38bFa98Ff2AF34081544BE0d1aA9C709D8283', 'latest', function(error, res)
if (error)
console.log("s")
))
大数据处理工具
以太坊内部总是以 wei 来表示余额(大整数),只有显示余额的时候,才转换为 ether 或其他单位。javascript 中默认的数字精度无法确切地表示 wei
webjs 中,自带 BigNumber 库
1 wei = 10 ^ 8
var BigNumber = require("bignumber.js")
var balance = new BigNumber("111111111111111111111111111111111111111111111111111");
console.log(balance)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IIu5F2zt-1643027019283)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642990205043.png)]
转化为十进制显示出来
默认保留小数点 20 位
var BigNumber = require("bignumber.js")
var balance = new BigNumber("111111111111111111111111111111111111111111111111111");
console.log(balance.toString(10))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Gy29wtOQ-1643027019284)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642990424963.png)]
检查参数
var BigNumber = require("bignumber.js")
var balance = new BigNumber("111111111111111111111111111111111111111111111111111");
var number = balance.toString(10)
var res = web3.utils.isBigNumber(number)
console.log(res)
res = web3.utils.isBigNumber(balance)
console.log(res)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-quezeQih-1643027019285)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642990785516.png)]
数值转换
wei 是最小的以太单位
console.log(web3.utils.fromWei('1', 'ether'))
console.log(web3.utils.fromWei('1', 'finney'))
console.log(web3.utils.fromWei('1', 'szabo'))
console.log(web3.utils.fromWei('1', 'shannon'))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qEHPUJyK-1643027019285)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642991061161.png)]
-
将给定的以太金额转换为以 wei 为单位的数值
console.log(web3.utils.toWei('1', 'ether')) console.log(web3.utils.toWei('1', 'finney')) console.log(web3.utils.toWei('1', 'szabo')) console.log(web3.utils.toWei('1', 'shannon'))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wXy7VFei-1643027019286)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642991201744.png)]
-
任意值转换为 16 进制字符串
数值字符串将解析为数值 文本字符串将解析为 utf8 字符串
console.log(web3.utils.toHex('234')) console.log(web3.utils.toHex(234))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zhHZgOyy-1643027019287)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642991355934.png)]
-
16 进制字符串转化为数值字符串
console.log(web3.utils.hexToNumberString('0xea'))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lPEaVjKx-1643027019288)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642991535524.png)]
-
杂七杂八转换
console.log(web3.utils.asciiToHex('abcdef')) console.log(web3.utils.hexToBytes('0x616263ea')) console.log(web3.utils.bytesToHex([97, 98, 99, 234]))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I6LjeSHK-1643027019289)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642991848259.png)]
-
检查是否为地址
console.log(web3.utils.isAddress('0x5B38Da6a701c568545dCfcB03FcB875f56beddC4'))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o0oSgxeH-1643027019289)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642992107282.png)]
区块操作
获取最新区块号
web3.eth.getBlockNumber().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V8H61W0s-1643027019290)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642992357531.png)]
指定块编号或块哈希对应的块
// 最新的块
web3.eth.getBlock('latest').then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sOAtKFXX-1643027019290)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642992923572.png)]
指定块的交易信息
web3.eth.getTransactionFromBlock('0x7fd5f696177d03b7dd882a93c18f6cfbe3fac8240f2c98f27c08c4586793e620', 0).then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ap5oRLwv-1643027019291)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642993710754.png)]
指定账号发出的交易数量
web3.eth.getBlockTransactionCount('0x7fd5f696177d03b7dd882a93c18f6cfbe3fac8240f2c98f27c08c4586793e620').then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FkRbQ6ru-1643027019291)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642993859176.png)]
账户相关操作
查询账户个数
返回当前节点控制的账户列表
web3.eth.getAccounts().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ILX3whhx-1643027019292)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642994036484.png)]
创建账户
web3.eth.personal.newAccount('!@abc').then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8LTjywcE-1643027019292)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642994386885.png)]
获得奖励的账户地址
web3.eth.getCoinbase().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hvqayT1F-1643027019293)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642994468876.png)]
是否正在挖矿
web3.eth.isMining().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XrlKTarO-1643027019293)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642994513355.png)]
交易相关
查询余额
获取指定块中特定只能账户地址的余额
web3.eth.getBalance(address [, defaultBlock] [, callback])
- defaultBlock:表执行到指定的区块时的余额
- 区块号
- 区块的 hash 值
- 字符串 “earliest”、“latest”、“pending”
web3.eth.getBalance('0x956188a6bD41694BdB13AA5CE168543a03B74770', function(error, result)
if (error)
console.log("something error.")
else
var balance = result.toString()
console.log(web3.utils.fromWei(balance, "ether"))
)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EIpyyZF9-1643027019294)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1642998200244.png)]
查询平均 gas 价格
获取当前 gas 价格,该价格由最近的若干块的 gas 价格中值决定
web3.eth.getGasPrice().then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LU9szHhI-1643027019294)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643001582680.png)]
发送交易
var transactionObject =
from: '0x956188a6bD41694BdB13AA5CE168543a03B74770',
to: '0x1a3D5055624707B689CA8130f72Abf41c461344B',
value: web3.utils.toWei('1', 'ether'),
data: web3.utils.toHex(234)
web3.eth.sendTransaction(transactionObject).then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CXEfFQOk-1643027019294)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643002813639.png)]
查询交易信息
web3.eth.getTransaction(transactionHash [, callback]) 返回具有指定哈希值的交易对象
- transactionHash - 交易哈希
web3.eth.getTransaction('0x11e1559508147c7ea2d3e9ce0dfb65be29d42d7a9077f9cef3e80ad64d38b3b8').then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UdfIEp1a-1643027019296)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643003220495.png)]
查询交易收据
也就是进区块数据
web3.eth.getTransactionReceipt(hash [,callback]) 返回指定交易的收据对象,如果交易处于 pending 状态,则返回 null
- 查询已经被打包进区块链的信息
web3.eth.getTransactionReceipt('0x11e1559508147c7ea2d3e9ce0dfb65be29d42d7a9077f9cef3e80ad64d38b3b8').then(console.log)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0sN8tmfB-1643027019296)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643003467342.png)]
与合约交互
ABI 简绍
相当于智能合约暴漏出来的标准接口
调用智能合约读函数
通常使用 call()
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
var abi = [
"inputs": [],
"name": "getNumber",
"outputs": [
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "uint256",
"name": "_number",
"type": "uint256"
],
"name": "setNumber",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
]
var contractAddress = '0x4E4861f95f4cB129Dae9E739458f1583E1100Dd1'
var myContract = new web3.eth.Contract(abi, contractAddress)
myContract.methods.getNumber().call(function(error, result)
console.log(result)
)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j3oocgFV-1643027019297)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643010370361.png)]
调用智能合约写函数
调用写函数,相当于发送了交易
myContract.methods.setNumber(1234)
.send( from: '0x956188a6bD41694BdB13AA5CE168543a03B74770' )
.on('receipt', function(receipt)
console.log(receipt)
)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hYLM6qGP-1643027019297)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643011318716.png)]
执行事件查询
合约部分
pragma solidity >= 0.7.0 <0.9.0;
contract DemoSimple
uint number;
event myEvent(uint name);
function setNumber(uint _number) public
emit myEvent(_number);
number = _number;
function getNumber() public view returns(uint)
return number;
js 部分
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
var abi = [
"anonymous": false,
"inputs": [
"indexed": false,
"internalType": "uint256",
"name": "name",
"type": "uint256"
],
"name": "myEvent",
"type": "event"
,
"inputs": [],
"name": "getNumber",
"outputs": [
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "uint256",
"name": "_number",
"type": "uint256"
],
"name": "setNumber",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
]
var contractAddress = '0x9af62672FA2a5f749Df1e3EdCE2A4825Adb73dF2'
var myContract = new web3.eth.Contract(abi, contractAddress)
myContract.getPastEvents(
'AllEvents',
fromBlock: 0,
toBlock: 'latest'
,
(error, result) => console.log(result)
)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gaFTqdJM-1643027019299)(C:\\Users\\Lenovo\\AppData\\Local\\Temp\\1643011858385.png)]
手工部署合约
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
var abi = [
"inputs": [
"internalType": "bytes32[]",
"name": "candidateNames",
"type": "bytes32[]"
],
"stateMutability": "nonpayable",
"type": "constructor"
,
"inputs": [
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"name": "candidateList",
"outputs": [
"internalType": "bytes32",
"name": "",
"type": "bytes32"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "bytes32",
"name": "candidate",
"type": "bytes32"
],
"name": "totalVotesFor",
"outputs": [
"internalType": "uint8",
"name": "",
"type": "uint8"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "bytes32",
"name": "candidate",
"type": "bytes32"
],
"name": "validCandidate",
"outputs": [
"internalType": "bool",
"name": "",
"type": "bool"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "bytes32",
"name": "candidate",
"type": "bytes32"
],
"name": "voteForCandidate",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
,
"inputs": [
"internalType": "bytes32",
"name": "",
"type": "bytes32"
],
"name": "votesReceived",
"outputs": [
"internalType": "uint8",以上是关于Web3js 小笔记的主要内容,如果未能解决你的问题,请参考以下文章
使用Ganache,web3js和remix在个人区块链上部署并调用合约