Talking about web3.0

Web1.0

It is the corporate operators of some browsers that produce the information and disseminate it in a way that is read-only by the user.

But people are gradually dissatisfied with only looking at the information pushed to them by the website, and have the desire to express

web2.0

The main body of online information producers: Not only large companies, ordinary users can also post articles and comments, and can create users on different websites, thereby increasing participation

Also provides some web applications, wordpress self-publishing platform

However: because information is an asset, it is already a consensus in the industry, but ordinary users as information creators do not have ownership of assets, and the huge profits generated through these digital assets are divided by the Internet platforms that actually own the data

Web3.0

New web interaction method: from the original "point-centralized server-point" data transmission to "point-point" data transmission, getting rid of the transition mode of the centralized server, improving the confidentiality of data, the efficiency of transmission, Really return data ownership to users

To put it simply: What web3.0 needs to do is to further realize "possessible" on the basis of "readable and writable"

web3.js && ethers.js

Both Web3.js and Ethers.js belong to the standard JavaScript API library of Ethereum. Both have their own characteristics and are also accepted by the majority of Web3 developers.

Web3.js is a relatively old API library with powerful functions, but you need to pay attention to various callback functions during use; Ethers.js is a newly emerging API library, and its biggest feature is that its interface is simple and convenient to call. It is friendly to developers who are familiar with JS.

web3.js

  • 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 object - web3.eth (specifically for interacting with the Ethereum blockchain) and shh object - web3.shh (for interacting with Whisper)
  • As a blockchain system, Ethereum has different end stages for a request. In order to meet such requirements, version 1.0.0 wraps the return value of this type of function call into a "promiEvent", which is a combination of promise and EventEmitter.
    PromiEvent is used like a promise, with the addition of .on, .once and .off methods

Commonly used 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

**Sync:** web3.version.node

**异步:**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 connection/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 the currently connected peer node
**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
v1.0.0: web3.givenProvider

set provider

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

web3 common tool method

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

同步: web3.eth.accounts
**异步:**web3.eth.getAccounts( (err, res)=>console.log(res) )
**v1.0.0:**web3.eth.getAccounts().then(console.log)

block related

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 )

Query the number of transactions in a block

**Synchronous: **web3.eth.getBlockTransactionCount( hashStringOrBlockNumber )
**Asynchronous: **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 (blocked)

** 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])

Trading partners:

from: sending address
to: receiving address, if you are creating a contract transaction, you can leave it blank
value: transaction amount, in wei, optional
gas: transaction gas consumption upper limit, optional
gasPrice: transaction gas unit price, optional
data: transaction carry string data, optional
nonce: integer nonce value, optional

message call

web3.eth.call(callObject [, defaultBlock][, callback])
Parameters:
call object: the same as the transaction object, but from is also optional
Default block: default "latest", you can pass in the specified block height
callback function, or synchronous call if None

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 the contract function

The contract function can be called directly through the created contract instance

// 直接调用,自动按函数类型决定用 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

The event of the contract is similar to filter, and filter options can be set to monitor

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);
	}
);

Ethers.js

The API in the Ethers.js library is mainly composed of 4 parts: Providers, Signers, Contract Interaction, Utilities

  1. Provider

Provider is an abstraction of Ethereum network connection, which provides a concise and consistent interface for standard Ethereum node functions

The more commonly used method in Provider is JsonRpcProvider, which allows connecting to a node network through JSON-RPC

// new ethers.providers.JsonRpcProvider([urlOrConnectionInfo[, networkish]])
const provider = new ethers.providers.JsonRpcProvider(
        'https://rpc.api.moonbase.moonbeam.network',
        {
    
    
            chainId: 1287,
            name: 'moonbase-alpha'
        }
);

In the above code example, JsonRpcProvider is used to connect to the Moonbase Alpha test network, in which not only the url parameters can be defined, but also the chainId and name of the network can be defined

  1. Signers

Signer is an abstraction of Ethereum accounts that can be used to sign messages and transactions, and send signed transactions to the Ethereum network to perform state change operations

The more commonly used method in Signer is Wallet, only Wallet can use the private key to sign transactions and information

// new ethers.Wallet(privateKey[, provider])
const alice = new ethers.Wallet(privateKeyAlice, provider);
const bob = new ethers.Wallet(privateKeyBob, provider);

const txReceipt = await alice.sendTransaction({
    
    
    to: bob.address,
    value: ethers.utils.parseEther('1.0')
});
await txReceipt.wait();

In the above code example, Wallet is used to define two Signers, alice and bob, and then alice calls the method sendTransaction() method to initiate a transaction to bob, and transfers the token of 1 ether

  1. Contract Interaction

Deploying a contract and generating a contract instance are inseparable from the two methods described below: ContractFactory() and Contract. For specific methods, see the code example interface below

// deploy contract
new ethers.ContractFactory(interface, bytecode[, signer])
contractFactory.deploy(..args)
contract.deployed()

// generate contract instance
new ethers.Contract(address, abi, signerOrProvider)

Among them, the interface parameter in ContractFactory represents the abi of the
contract compiled by Hardhat, and its abi and bytecode and other compilation information are stored in the artifacts/contracts/CONTRACT_NAME.json file in the root directory of the project

  1. Utilities

The various methods provided under utilities are more like various tools. The more commonly used ones include operations on BigNumber, direct conversion of Ethereum Token units, and tools for converting strings to bytes32. Here are a few common ones. method

// BigNumber
BigNumber.toNumber() => number
BigNumber.toHexString() => string<DataHexString>

// Display Logic and Input
ethers.utils.parseEther(string) => BigNumber
ethers.utils.formatEther(value(BigNumber)) => string

// Strings
ethers.utils.parseBytes32String(aBytesLike) => string
ethers.utils.formatBytes32String(text) => string<DataHexString<32>>

BigNumber.toNumber(): converts the value of BigNumber to a JavaScript value

BigNumber.toHexString(): Convert the BigNumber value to a hexadecimal value starting with 0x

ethers.utils.parseEther(string): Convert an integer to a large integer in ether

ethers.utils.formatEther(value(BigNumber)): converts a large integer to an integer in ether

ethers.utils.parseBytes32String(aBytesLike): returns a decoded string represented by bytes 32 encoded data

ethers.utils.formatBytes32String(text): returns the bytes 32 string representation of the text

Moonbeam

The Moonbeam platform uses integrated cross-chain messaging, allowing developers to create smart contracts that access multiple remote blockchain services. In this way, Moonbeam's developer-friendly EVM platform, various tool support and Substrate architecture are combined to provide an ideal development environment for building interconnected applications. Author: Moonbeam community https://www.bilibili.com/read/cv18976490 Source: bilibili

Guess you like

Origin blog.csdn.net/qq_42035031/article/details/128029022