《深入掌握以太坊核心技术》--12-Web3.js简介
web3 .js简介
- Web3 JavaScript app APl
- web3.js是一个JavaScriptAPI库。要使DApp在以太坊上运行我们可以使用web3.js库提供的web3对象
- web3.js通过RPC调用与本地节点通信,它可以用于任何暴露了RPC层的以太坊节点
- web3包含eth对象-web3.eth(专门与以太坊区块链交互)和shh 对象-web3.shh(用于与 Whisper 交互)
web3 模块加载
- 首先需要将 web3 模块安装在项目中;
npm instaN web3@0.20.1
- 然后创建一个 web3 实例,设置一个“prowder"
- 为了保证我们的 MetaMas* 设置好的 proxider不被覆掉。在引入web3 之前我们一般要做当前环境检查(以0.20.1为例):
if{typeof web3 1== 'undefined? {
web3 = new Web3(web3.currentProwider };
}else {
web3 = new Web3(new Web3.prowiders
.HttpProvider("http/ocalhost:8545"));
}
异步回调(callback)
在Web3.js中,同步(synchronous)和异步(asynchronous)是用来描述函数调用方式的概念。
同步(Synchronous):同步函数调用是指在执行函数时,程序会一直等待该函数执行完毕并返回结果,然后再继续执行下一步操作。在同步调用中,代码按照顺序逐行执行,直到当前函数执行完成才会执行下一个函数。这意味着当一个同步函数被调用时,程序会被阻塞,直到该函数执行完成。
例如,在Web3.js中,当你调用一个同步的以太坊智能合约方法时,程序会等待合约方法执行完成并返回结果,然后再继续执行下一行代码。
异步(Asynchronous):异步函数调用是指在执行函数时,程序不会等待该函数执行完毕,而是立即继续执行下一步操作。在异步调用中,函数的执行不会阻塞程序的执行,而是在后台执行。通常,在异步函数执行完成后,会通过回调函数、Promise对象或者async/await语法来获取结果或者处理返回值。
例如,在Web3.js中,当你调用一个异步的以太坊智能合约方法时,程序会立即继续执行下一行代码,而不会等待合约方法执行完成。你可以通过回调函数或Promise来获取方法执行的结果或处理返回值。
- web3jsAPI设计的最初目的,主要是为了和本地RPC节点共同使用,所以默认情况下发送的是同步HTTP请求
- 如果要发送异步请求,可以在函数的最后一个参数位置上,传入一个回调函数。回调函数是可选(optioanl)的
- 我们一般采用的回调风格是所谓的“错误优先”,例如:
web3.eth.getBlock(48, function(error, result){
if(!error)
console.log(jsoN.stringify(result));
else
console.error(error);
})
注意:同步只能保证顺序执行,但会卡住,但异步不会出现这个情况,同时Dapp一般是异步的
回调 Promise 事件(v1.0.0)
- 为了帮助web3集成到不同标准的所有类型项目中,1.0.0版本提供了多种方式来处理异步函数。大多数的web3对象允许将一个回调函数作为最后一个函数参数传入,同时会返回一个promise用于链式函数调用。
- 以太坊作为一个区块链系统,一次请求具有不同的结束阶段。为了满足这样的要求,1.0.0版本将这类函数调用的返回值包成一个“承诺事件”(promiEvent),这是一个promise和EventEmitter的结合体。
- PromiEvent的用法就像promise一样,另外还加入了.on,.once和.off方法
web3.eth,sendTransaction({from:'0x123..., data:'0x432...'})
.once('transactionHash', function(hash){.. })
.once('receipt', function(receipt){ ... })
.on('confirmation', function(confNumber, recelpt){ ... })
.on('error', function(error){ ... })
.then(function(receipt){ //will be fired once the receipt is mined });
应用二进制接口(ABI)
-
web3.js通过以太坊智能合约的json接口(ApplicationBinary
Interface,ABI)创建一个JavaScript 对象,用来在js代码中描述 -
函数(functions)
- type:函数类型,默认“function”,也可能是“constructor
- constant,payable,stateMutability:函数的状态可变性
- inputs,outputs: 函数输入、输出参数描述列表
-
事件(events)
- type:类型,总是“event”
- inputs:输入对象列表,包括name、type、indexed
批处理请求(batch requests)
- 批处理请求允许我们将请求排序,然后一起处理它们。
- 注意:批量请求不会更快。实际上,在某些情况下,一次性地发出许多请求会更快,因为请求是异步处理的。
- 批处理请求主要用于确保请求的顺序,并串行处理
var batchweb3.createBatch(),;batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000','latest',callback));
batch.add(web3.eth.contract(abi).at(address).balance.request(address, callback2));
batch.execute();
大数处理(big numbers)
- Javascript中默认的数字精度较小,所以web3.js 会自动添加一个依赖库 BigNumber,专门用于大数处理
- 对于数值,我们应该习惯把它转换成BigNumber对象来处理
var balance = new BigNumber('131242344353464564564574574567456’)
//or war bolance = web3.eth.getBalance(someAddress);
balance,plus(21).toString(10);//"131242344353464564564574574567477"
- BigNumbertostring(10)对小数只保留20位浮点精度。所以推荐的做法是,我们内部总是用wel来表示余额(大整数),只有在需要显示给用户看的时候才转换为ether或其它单位
常用 API
后面有[]的为可选参数
基本信息查询
查看web3 版本
-
v0.2x.x:web3.version.api
-
v1.0.0:web3.version
查看web3连接到的节点版本(clientVersion) -
同步:web3.version.node
-
异步:
- web3.version.getNode((error,result)=>{console.log(result)})
-
v1.0.0:web3.eth.getNodelnfo().then(console.log)
获取network id
- 同步:web3.version.network
- 异步:web3.version.getNetwork((err,res)=>{console.log(res)})
- v1.0.0:web3.eth.net.getld().then(console.log)
获取节点的以太坊协议版本
- 同步:web3.wersion.ethereum
- 异步:web3.version.getEthereum((err, res)=>{console.og(res)})
- v1.0.0:web3.eth.getProtocolVersion().then(console.log)
网络状态查询
是否有节点连接监昕,返回tnue/false
- 同步:web3.isConnect)或者web3.net.listening
- 异步:web3.net.getListening((err,res)=>console.log(res))
- v1.0.0:web3.eth.net.isListening().then(console.log)
查春当前连接的peer节点
- 同步:web3.net.peerCount
- .异步:web3.net.getPeerCount((err,res)=>console.log(res))
- v1.0.0:web3.eth.net.getPeerCount(),then(console.log)
Provider
在Web3中,Provider通常是指用于连接应用程序与区块链网络之间的软件组件或服务。它提供了一种接口,使应用程序能够与区块链进行交互,包括发送交易、读取数据等操作。Provider可以是多种形式的,例如:
本地节点(Local Node):用户可以在本地运行一个完整的节点软件,如Geth(以太坊客户端)或Parity(另一个以太坊客户端)。本地节点提供了直接连接到区块链网络的方式,但需要用户自行维护和管理节点。
远程托管节点(Remote Hosted Node):一些公司或服务提供商提供了托管的区块链节点,用户可以通过HTTP或WebSocket等协议连接到这些节点。这种方式不需要用户自行运行节点,但需要信任节点提供商。
基础设施提供商(Infrastructure Provider):例如Infura,它提供了以太坊节点的API服务,使开发者能够通过简单的HTTP请求与以太坊网络进行交互。这种方式简化了与区块链的交互,但也需要信任提供商。
针对特定协议的API服务(Protocol-Specific API Service):有些区块链协议提供了自己的API服务,开发者可以通过这些服务与相应的区块链网络进行交互。例如,以太坊提供了以太坊JSON-RPC API,可以通过HTTP或WebSocket连接到以太坊网络。
查看当前设置的web3provider
- web3.currentProvider
查看浏览器环境设置的web3provider(v1.0.0)
- web3.givenProvider
设置 provider
-
web3.setProvider(provider)
- web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545’))
web3 通用工具方法
以太单位转换
- web3.fromWei web3.toWei
数据类型转换
- web3.toString web3.toDecimal web3.toBigNumber
字符编码转换
- web3.toHex web3.toAscii web3.toUtf8 web3.fromUtf8
地址相关
- web3.isAddress web3.toChecksumAddress
web3.eth
账户相关
coinbase 查询
- 同步: web3.eth.coinbase
- 异步: web3.eth.getCoinbase((err,res)=>console.log(res))
- v1.0.0: web3.eth.getCoinbase().then(console.log)
账户查询
- 同步:web3.eth.accounts
- 异步:web3.eth.getAccounts((err,res)=>console.log(res))
- v1.0.0:web3.eth.getAccounts().then(console.log
区块相关
区块高度查询
- 同步:web3.eth.blockNumber
- 异步:web3.eth.getBlockNumber( calback )
gasPrice 查询
-
同步:web3.eth.gasPrice
-
异步:web3.eth.getGasPrice( callback )
区抉查询
- 同步:web3.eth.getBlock(hashStringOrBlockNumber[ returnTransactionObjects] )
- 异步:web3.eth.getBlock(hashStringOrBlockNumber,callback )
块中交易数最查询
- 同步: web3.eth.getBlockTransactionCount( hashstringOrBlockNumber)
- 异步: web3.eth.getBlockTransactionCount( hashStringOrBlockNumber,calback)
交易相关
余额查询
- 同步:web3.eth.getBalance(addressHexString [, defaultBlock])(可选参数)
- 异步:web3.eth.getBalance(addressHexString [, defaultBlock] [, calback])
交易查询
- 同步:web3.eth.getTransaction(transactionHash)
- 异步:web3.eth.getTransaction(transactionHash [, callback])
交易执行相关
-
交易收据查询(已进块)
-
同步:web3.eth.getTransactionReceipt(hashString)
-
异步:web3.eth.getTransactionReceipt(hashString [, callback])
-
估计 gas消耗量
-
同步:web3.eth.estimateGas(cal0bject)
-
异步:web3.eth.estimateGas(cal0bject [, calback])
发送交易
-
web3.eth.sendTransaction(transactionObject [, callback])
-
交易对象:
- from:发送地址
- to:按收地址,如果是创建合约交易,可不填
- walue;交易金额,以wel为单位,可选
- gas:交易消耗gas上限,可选
- gasPrice;交易gas单价,可选
- data:交易携带的字巾数据。可选
- nonce:整数nonce值,可选
消息调用
- web3.eth.call(callobject [, defaultBlock] l, calback])
- 参数:
-
调用对象:与交易对象相网,只是trom也是可选的
-
默认区块:默认“latest”。可以传入指定的区块高度
-
同调函数,如果没有则为同步调用
-
var result = web3.eth.call{{to:"0xcdobd0339eb8d57087278718986382264244252f",
data:
0xc6888fe100000000000000003"}};//(函数选择器:0x合约+000+参数)
console.log(result):
日志过滤(事件监听)
-
web3.eth.filter( filterÃptions [ , calback ])
// flterstring可以是'latest ' or 'pending' var filter = web3.eth.filter(fterString); // 或者可以填入一个日志过滤 options var filter = web3.eth.filter(options), //监听日志变化 filterwatch(function(error, result){if [!error) console.log[result];} ); // 还可以用传入回调函数的方法。立刻开始监听日志 web3.eth.filte[options, function[error, resule){if (lerror] console.log(result); });
合约相关
创建合约
- web3.eth.contract
var MyContract = web3.eth.contract(abiArray)(传入API)
var contractinstance= MyContract.at(address);// 通过地址初始化合约实例
var contractinstance= Mycontract.new{[constructorParam1]
[,constructorParam2], {data: '0x12345(字节码)..',from: myAccount,gas: 1000000}};//或者部罢一个新合约
调用合约函数
监听合约事件
先定义后启动,或者直接监听