Basic usage of Web3.js (interaction with Ethereum smart contracts)

Introduction to web3.js

• Web3 JavaScript app API

• web3.js is a JavaScript API library. To make the DApp run on Ethereum, we can use the web3 object provided by the web3.js library

• web3.js communicates with local nodes via RPC calls, it can be used on any Ethereum node that exposes the RPC layer

• web3 contains the eth object - web3.eth (for interacting with the Ethereum blockchain) and the shh object - web3.shh (for interacting with Whisper)

web3 module loading

• First, you need to install the web3 module in the project: npm install [email protected]
• Then create a web3 instance and set a "provider" • In order to ensure that the provider set by our MetaMask is not overwritten, before introducing web3, we Generally do the current environment check (take v0.20.1 as an example):

if (typeof web3 !== 'undefined') {
    
     
web3 = new Web3(web3.currentProvider); 
} else {
    
    
web3 = new Web3(new Web3.providers
.HttpProvider("http://localhost:8545")); 
}

Asynchronous callback (callback)

• The original purpose of web3js API design is mainly for use with local RPC nodes, so synchronous HTTP requests are sent by default

• If you want to send an asynchronous request, you can pass a callback function in the last parameter position of the function. The callback function is optional (optioanl)

• The callback style we generally use is what is called "error first", eg:

web3.eth.getBlock(48, function(error, result){
    
     
if(!error) 
console.log(JSON.stringify(result)); 
else 
console.error(error); 
});

Callback for Promise events (v1.0.0)

• To help integrate web3 into all types of projects across different standards, version 1.0.0 provides several ways to handle asynchronous functions. Most web3 objects allow a callback function to be passed in as the last function argument, and return a promise for chaining function calls.

• As a blockchain system, a request has different end stages. In order to meet this requirement, version 1.0.0 wraps the return value of such function calls into a "promise event" (promiEvent), which is a combination of promise and EventEmitter.

• PromiEvent is used like a promise, with the addition of .on, .once and .off methods

web3.eth.sendTransaction({
    
    from: '0x123...', data: '0x432...'}) 
.once('transactionHash', function(hash){
    
     ... }) 
.once('receipt', function(receipt){
    
     ... }) 
.on('confirmation', function(confNumber, receipt){
    
     ... }) 
.on('error', function(error){
    
     ... }) 
.then(function(receipt){
    
     
// will be fired once the receipt is mined });

Application Binary Interface (ABI) • web3.js creates a JavaScript object through the json interface (Application Binary Interface, ABI) of the Ethereum smart contract, which is used to
describe in the js code

• function (functions) • type: function type, default "function", may also be "constructor" • constant, payable, stateMutability: function's state mutability
• inputs, outputs: function input, output parameter description list
• events (events) • type: type, always "event" • inputs: list of input objects, including name, type, indexed
batch requests (batch requests) • batch requests allow us to order requests, and then process them together.

• Note: Bulk requests will not be faster. In fact, in some cases it can be faster to make many requests at once because the requests are handled asynchronously.

• Batch requests are mainly used to ensure the order of requests and are processed serially.

var batch = web3.createBatch(); 
batch.add(web3.eth.getBalance.request('0x0000000000000000
000000000000000000000000', 'latest', callback)); 
batch.add(web3.eth.contract(abi).at(address).balance.request(a
ddress, callback2)); 
batch.execute();

Common API - Basic Information Query

View web3 version

• v0.2x.x:web3.version.api
• v1.0.0:web3.version

View the node version (clientVersion) that web3 is connected to

• Synchronous: web3.version.node
• Asynchronous: web3.version.getNode((error,result)=>{console.log(result)})
• v1.0.0: web3.eth.getNodeInfo().then(console. log)

Basic information query

get network id

• Synchronous: web3.version.network
• Asynchronous: web3.version.getNetwork((err, res)=>{console.log(res)})
• v1.0.0: web3.eth.net.getId().then( console.log)

Get the Ethereum protocol version of the node

• Synchronous: web3.version.ethereum
• Asynchronous: web3.version.getEthereum((err, res)=>{console.log(res)})
• v1.0.0: web3.eth.getProtocolVersion().then(console. log)

Network status query

Whether there is a node connected/listening, return true/false

• Synchronous: web3.isConnect() or web3.net.listening
• Asynchronous: web3.net.getListening((err,res)=>console.log(res))
• v1.0.0: web3.eth.net.isListening( ).then(console.log)

View currently connected peer nodes

• Synchronous: web3.net.peerCount
• Asynchronous: web3.net.getPeerCount((err,res)=>console.log(res))
• v1.0.0: web3.eth.net.getPeerCount().then(console. log)

Provider

View the currently set web3 provider

• web3.currentProvider

View web3 provider (v1.0.0) set by browser environment • web3.givenProvider

set provider

• web3.setProvider(provider)
• web3.setProvider(new web3.providers.HttpProvider(‘http://localhost:8545’))

web3 general tool approach

Ether Unit Conversion

• web3.fromWei web3.toWei

data type conversion

• web3.toString web3.toDecimal web3.toBigNumber

character encoding conversion

• web3.toHex web3.toAscii web3.toUtf8 web3.fromUtf8

address related

• web3.isAddress web3.toChecksumAddress
web3.eth – account related

coinbase query

• Synchronous: web3.eth.coinbase
• Asynchronous: web3.eth.getCoinbase( (err, res)=>console.log(res) )
• v1.0.0: web3.eth.getCoinbase().then(console.log)

Account Inquiry

• Synchronous: web3.eth.accounts
• Asynchronous: web3.eth.getAccounts( (err, res)=>console.log(res) )
• v1.0.0: web3.eth.getAccounts().then(console.log)

Block correlation

Block height query

• Synchronous: web3.eth.blockNumber
• Asynchronous: web3.eth.getBlockNumber( callback )

gasPrice query

• Synchronous: web3.eth.gasPrice
• Asynchronous: web3.eth.getGasPrice( callback )

block query

• 同步:web3.eth.getBlockNumber( hashStringOrBlockNumber
[ ,returnTransactionObjects] )
• 异步:web3.eth.getBlockNumber( hashStringOrBlockNumber, callback )
块中交易数量查询
• 同步:
web3.eth.getBlockTransactionCount( hashStringOrBlockNumber ) • 异步:
web3.eth.getBlockTransactionCount( hashStringOrBlockNumber
, callback )

Transaction related

Balance inquiry

• 同步:web3.eth.getBalance(addressHexString [, defaultBlock])
• 异步:web3.eth.getBalance(addressHexString [, defaultBlock]
[, callback])

Transaction inquiry

• Synchronous: web3.eth.getTransaction(transactionHash)
• Asynchronous: web3.eth.getTransaction(transactionHash [, callback])

Transaction execution related
• Transaction receipt query (block entered)
• Synchronous: web3.eth.getTransactionReceipt(hashString)
• Asynchronous: web3.eth.getTransactionReceipt(hashString [, callback])
• Estimated gas consumption
• Synchronous: web3.eth. estimateGas(callObject)
• Asynchronous: web3.eth.estimateGas(callObject [, callback])

send transaction

• web3.eth.sendTransaction(transactionObject [, callback])
• Transaction object:
• from: sending address
• to: receiving address, if it is a contract creation transaction, it can be left blank
• value: transaction amount, in wei, optional
• gas: the upper limit of gas consumed by the transaction, optional
• gasPrice: the unit gas price of the transaction, optional
• data: the string data carried by the transaction, optional
• nonce: the integer nonce value, optional

message call

• web3.eth.call(callObject [, defaultBlock] [, callback])
• Parameters:
• Call object: same as transaction object, except that from is optional
• Default block: default "latest", which can be passed in the specified Block height
• Callback function, if none is called synchronously

var result = web3.eth.call({
    
     to: 
"0xc4abd0339eb8d57087278718986382264244252f", 
data: 
"0xc6888fa100000000000000000000000000000000000000000000000000
0 0000000000003" }); 
console.log(result);

Log filtering (event monitoring)

web3.eth.filter( filterOptions [ , callback ] )
// filterString 可以是 'latest' or 'pending' 
var filter = web3.eth.filter(filterString); 
// 或者可以填入一个日志过滤 options 
var filter = web3.eth.filter(options); 
// 监听日志变化
filter.watch(function(error, result){
    
     if (!error) console.log(result); }); 
// 还可以用传入回调函数的方法,立刻开始监听日志
web3.eth.filter(options, function(error, result){
    
     
if (!error) console.log(result); 
});

Contract related - create a contract

web3.eth.contract
var MyContract = web3.eth.contract(abiArray); 
// 通过地址初始化合约实例
var contractInstance = MyContract.at(address); 
// 或者部署一个新合约
var contractInstance = MyContract.new([constructorParam1] 
[, constructorParam2], {
    
    data: '0x12345...', from: 
myAccount, gas: 1000000});

call contract function

• 可以通过已创建的合约实例,直接调用合约函数
// 直接调用,自动按函数类型决定用 sendTransaction 还是 call
myContractInstance.myMethod(param1 [, param2, ...] [, 
transactionObject] [, defaultBlock] [, callback]); 
// 显式以消息调用形式 call 该函数
myContractInstance.myMethod.call(param1 [, param2, ...] [, 
transactionObject] [, defaultBlock] [, callback]); 
// 显式以发送交易形式调用该函数
myContractInstance.myMethod.sendTransaction(param1 [, 
param2, ...] [, transactionObject] [, callback]); 

Listen to contract events

• 合约的 event 类似于 filter,可以设置过滤选项来监听
var event = myContractInstance.MyEvent({
    
    valueA: 23} 
[, additionalFilterObject]) 
// 监听事件
event.watch(function(error, result){
    
     if (!error) console.log(result); }); 
//还可以用传入回调函数的方法,立刻开始监听事件
var event = myContractInstance.MyEvent([{
    
    valueA: 23}] 
[, additionalFilterObject] , function(error, result){
    
     
if (!error) console.log(result); 
}
);

Guess you like

Origin blog.csdn.net/david2000999/article/details/120176244