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]) 返回具有指定哈希值的交易对象
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",
"name": "",
"type": "uint8"
}],
"stateMutability": "view",
"type": "function"
}
]
var myContract = new web3.eth.Contract(abi)
// deplay 的 字节码
var data = "0x60806040523480156200001157600080fd5b50604051620007d9380380620007d983398181016040528101906200003791906200028c565b80600190805190602001906200004f92919062000057565b5050620002dd565b82805482825590600052602060002090810192821562000096579160200282015b828111156200009557825182559160200191906001019062000078565b5b509050620000a59190620000a9565b5090565b5b80821115620000c4576000816000905550600101620000aa565b5090565b6000604051905090565b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6200012c82620000e1565b810181811067ffffffffffffffff821117156200014e576200014d620000f2565b5b80604052505050565b600062000163620000c8565b905062000171828262000121565b919050565b600067ffffffffffffffff821115620001945762000193620000f2565b5b602082029050602081019050919050565b600080fd5b6000819050919050565b620001bf81620001aa565b8114620001cb57600080fd5b50565b600081519050620001df81620001b4565b92915050565b6000620001fc620001f68462000176565b62000157565b90508083825260208201905060208402830185811115620002225762000221620001a5565b5b835b818110156200024f57806200023a8882620001ce565b84526020840193505060208101905062000224565b5050509392505050565b600082601f830112620002715762000270620000dc565b5b815162000283848260208601620001e5565b91505092915050565b600060208284031215620002a557620002a4620000d2565b5b600082015167ffffffffffffffff811115620002c657620002c5620000d7565b5b620002d48482850162000259565b91505092915050565b6104ec80620002ed6000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c80632f265cf71461005c578063392e66781461008c5780637021939f146100bc578063b13c744b146100ec578063cc9ab2671461011c575b600080fd5b610076600480360381019061007191906102b1565b610138565b60405161008391906102fa565b60405180910390f35b6100a660048036038101906100a191906102b1565b610173565b6040516100b39190610330565b60405180910390f35b6100d660048036038101906100d191906102b1565b6101d6565b6040516100e391906102fa565b60405180910390f35b61010660048036038101906101019190610381565b6101f6565b60405161011391906103bd565b60405180910390f35b610136600480360381019061013191906102b1565b61021a565b005b600061014382610173565b61014c57600080fd5b60008083815260200190815260200160002060009054906101000a900460ff169050919050565b600080600090505b6001805490508110156101cb57826001828154811061019d5761019c6103d8565b5b906000526020600020015414156101b85760019150506101d1565b80806101c390610436565b91505061017b565b50600090505b919050565b60006020528060005260406000206000915054906101000a900460ff1681565b6001818154811061020657600080fd5b906000526020600020016000915090505481565b61022381610173565b61022c57600080fd5b600160008083815260200190815260200160002060008282829054906101000a900460ff1661025b919061047f565b92506101000a81548160ff021916908360ff16021790555050565b600080fd5b6000819050919050565b61028e8161027b565b811461029957600080fd5b50565b6000813590506102ab81610285565b92915050565b6000602082840312156102c7576102c6610276565b5b60006102d58482850161029c565b91505092915050565b600060ff82169050919050565b6102f4816102de565b82525050565b600060208201905061030f60008301846102eb565b92915050565b60008115159050919050565b61032a81610315565b82525050565b60006020820190506103456000830184610321565b92915050565b6000819050919050565b61035e8161034b565b811461036957600080fd5b50565b60008135905061037b81610355565b92915050565b60006020828403121561039757610396610276565b5b60006103a58482850161036c565b91505092915050565b6103b78161027b565b82525050565b60006020820190506103d260008301846103ae565b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b60006104418261034b565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82141561047457610473610407565b5b600182019050919050565b600061048a826102de565b9150610495836102de565b92508260ff038211156104ab576104aa610407565b5b82820190509291505056fea2646970667358221220e57aa680dcacd545ddb2ee24becb89e702befa239b7528943815111c8cf540ef64736f6c634300080b0033"
var candidateNames = ['0x416c696365', '0x4265747479', '0x5365615361']
myContract.deploy({
data: data,
arguments: [candidateNames]
}).send({
from: '0x88F3f579A8f1A84376884286Bd4A7927593834D7',
gas: 1500000,
gasPrice: '1000000'
}, function(error, result) {
console.log(result)
})
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mOlQXBWo-1643027019299)(C:\Users\Lenovo\AppData\Local\Temp\1643014387962.png)]
|