Catalog title
- web3.js introduction
- web3 module loading
- Common API - basic information query
- web3 general tools and methods
web3.js introduction
Web3 JavaScript app API
web3.js is a JavaScript API library. To make DApp run on Ethereum, we can use Web3 Web3 object provided by JS Library
web3.js communicates with local nodes through RPC calls. It can be used for any Ethereum node that exposes the RPC layer
web3 contains eth objects - web3 Eth (specifically interacting with Ethereum blockchain) and shh objects - web3 shh (for interacting with Whisper)
web3 module loading
First, you need to install the Web3 module in the project: npm install web3@0.20.1
Then create a web3 instance and set up a "provider". In order to ensure that the provider set by our MetaMask is not overwritten, we generally need to check the current environment before introducing web3 (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
The original purpose of web3js API design is mainly to use with local RPC nodes, so synchronous HTTP requests are sent by default
If you want to send an asynchronous request, you can pass in a callback function at the last parameter of the function. The callback function is optional
The callback style we generally adopt is the so-called "error first", for example:
web3.eth.getBlock(48, function(error, result){ if(!error) console.log(JSON.stringify(result)); else console.error(error); });
Callback Promise event (v1.0.0)
To help web3 integrate into all types of projects with different standards, version 1.0.0 provides a variety of ways to handle asynchronous functions. Most web3 objects allow a callback function to be passed in as the last function parameter and return a promise for chain function calls.
As a blockchain system, Ethereum has different end stages for one request. In order to meet such requirements, version 1.0.0 packages the return value of such function calls into a "promise event", which is a combination of promise and EventEmitter.
The usage of promiseevent is like promise. In addition, it is added on,. once and off method
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 Application Binary Interface (ABI) of Ethereum smart contract, which is used in js
Description in code
functions type: function type, default "function", or "constructor" constant, payable, stateMutability: the state variability of the function
inputs, outputs: description list of function input and output parameters
Event type: type, always "event" inputs: list of input objects, including name, type and indexed
Batch requests batch requests allow us to sort requests and then process them together.
Note: bulk requests will not be faster. In fact, in some cases, it's faster to make many requests at once because the requests are processed asynchronously.
Batch requests are mainly used to ensure the order of requests and serial processing.
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 version of the node to which web3 is connected (clientVersion)
Sync: 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
Sync: 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
Sync: 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 node connection / listening, return true/false
Sync: 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 the currently connected peer node
Sync: 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
web3 provider (v1.0.0) for viewing browser environment settings givenProvider
Set up provider
web3.setProvider(provider)
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'))
web3 general tools and methods
Ethernet 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
Sync: Web3 eth. coinbase
Asynchronous: Web3 eth. getCoinbase( (err, res)=>console. log(res) )
v1.0.0: web3.eth.getCoinbase().then(console.log)
Account inquiry
Sync: 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
Sync: Web3 eth. blockNumber
Asynchronous: Web3 eth. getBlockNumber( callback )
gasPrice query
Sync: Web3 eth. gasPrice
Asynchronous: Web3 eth. getGasPrice( callback )
Block query
? Synchronization: web3.eth.getBlockNumber( hashStringOrBlockNumber [ ,returnTransactionObjects] ) ? Asynchronous: web3.eth.getBlockNumber( hashStringOrBlockNumber, callback ) Transaction quantity query in block ? Synchronization: web3.eth.getBlockTransactionCount( hashStringOrBlockNumber ) ? Asynchronous: web3.eth.getBlockTransactionCount( hashStringOrBlockNumber , callback )
Transaction related
Balance query
Sync: Web3 eth. getBalance(addressHexString [, defaultBlock])
Asynchronous: Web3 eth. getBalance(addressHexString [, defaultBlock]
[, callback])
Transaction query
Sync: Web3 eth. getTransaction(transactionHash)
Asynchronous: Web3 eth. getTransaction(transactionHash [, callback])
Transaction execution related
Transaction receipt query (block entered)
Sync: Web3 eth. getTransactionReceipt(hashString)
Asynchronous: Web3 eth. getTransactionReceipt(hashString [, callback])
Estimated gas consumption
Sync: Web3 eth. estimateGas(callObject)
Asynchronous: Web3 eth. estimateGas(callObject [, callback])
Send transaction
web3.eth.sendTransaction(transactionObject [, callback])
Trading partner:
from: sending address
to: receiving address; optional if it is a contract transaction
value: transaction amount, in wei; optional
Gas: transaction consumption gas upper limit, optional
gasPrice: transaction gas unit price, optional
Data: String data carried by the transaction, optional
Nonce: integer nonce value, optional
Message call
web3.eth.call(callObject [, defaultBlock] [, callback])
Parameters:
Call object: the same as the transaction object, except that from is also optional
Default block: the default is "latest", and the specified block height can be passed in
Callback function. If not, it is called synchronously
var result = web3.eth.call({ to: "0xc4abd0339eb8d57087278718986382264244252f", data: "0xc6888fa100000000000000000000000000000000000000000000000000 0 0000000000003" }); console.log(result);
Log filtering (event listening)
web3.eth.filter( filterOptions [ , callback ] ) // filterString can be 'latest' or 'pending' var filter = web3.eth.filter(filterString); // Or you can fill in a log filtering option var filter = web3.eth.filter(options); // Monitor log changes filter.watch(function(error, result){ if (!error) console.log(result); }); // You can also use the method of passing in the callback function to immediately start listening to the log web3.eth.filter(options, function(error, result){ if (!error) console.log(result); });
Contract related - create contract
web3.eth.contract var MyContract = web3.eth.contract(abiArray); // Initialize contract instance by address var contractInstance = MyContract.at(address); // Or deploy a new contract var contractInstance = MyContract.new([constructorParam1] [, constructorParam2], {data: '0x12345...', from: myAccount, gas: 1000000});
Call contract function
? You can directly call the contract function through the created contract instance // Call directly, and automatically decide whether to use sendTransaction or call according to the function type myContractInstance.myMethod(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]); // Call the function explicitly as a message call myContractInstance.myMethod.call(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]); // This function is explicitly called as a send transaction myContractInstance.myMethod.sendTransaction(param1 [, param2, ...] [, transactionObject] [, callback]);
Monitoring contract events
? Contractual event be similar to filter,You can set filtering options to listen var event = myContractInstance.MyEvent({valueA: 23} [, additionalFilterObject]) // Listening events event.watch(function(error, result){ if (!error) console.log(result); }); //You can also use the method of passing in the callback function to immediately start listening for events var event = myContractInstance.MyEvent([{valueA: 23}] [, additionalFilterObject] , function(error, result){ if (!error) console.log(result); } );