What is Web3?

What is Web3?

Web3 is the next generation of the Internet, built on blockchain technology, which enables the development and use of decentralized applications (DApps). Web3 is a new Internet protocol that transforms the Internet from a centralized client-server model to a decentralized peer-to-peer network.

At the core of Web3 is the Ethereum blockchain, an open blockchain platform that can be used to create and run smart contracts. A smart contract is an automated computer program that can execute transactions and agreements without a middleman. Ethereum aims to be a global computer that anyone can use to run DApps.

Advantages of Web3

The advantage of Web3 is that it enables decentralized applications, which means it can provide greater security, transparency and reliability. Web3's decentralized model can avoid problems such as single points of failure and data leakage, thereby improving application reliability and availability. Additionally, Web3 can provide users with more privacy and security as it allows them to remain anonymous and in control of their data.

Web3 applications

Web3 has a wide range of applications, and it can be used to create various types of DApps, including cryptocurrency wallets, decentralized exchanges, games, social networks, and more. Web3 can also be used to create smart contracts, which can be used to execute various agreements and transactions, including voting, crowdfunding, IoT devices, and more.

Connecting Ethereum nodes using Web3.js

To develop and use Web3 applications, you need to use some tools and techniques. The most important of these is the Web3.js library, which is a JavaScript library that can be used to connect to Ethereum nodes and perform various operations, including querying account balances, creating and sending transactions, interacting with smart contracts, and more.

The following is a sample code that uses Web3.js to connect to an Ethereum node and query the account balance:

// 引入Web3.js库
const Web3 = require('web3');

// 创建Web3实例,连接以太坊节点
const web3 = new Web3('https://mainnet.infura.io/v3/your-project-id');

// 查询账户余额
web3.eth.getBalance('0x1234567890123456789012345678901234567890')
    .then(balance => {
    
    
        console.log(`账户余额:${
      
      web3.utils.fromWei(balance, 'ether')} ETH`);
    })
    .catch(error => {
    
    
        console.error(error);
    });

The above code uses the public node provided by Infura to connect to the Ethereum main network and query the balance of the specified account. Among them, web3.eth.getBalance()the method is used to query the account balance, and web3.utils.fromWei()the method is used to convert the balance from Wei to ETH.

Create and send Ethereum transactions using Web3.js

In addition to querying account balances, Web3.js can also be used to create and send Ethereum transactions. Here is a sample code for creating and sending an Ether transaction using Web3.js:

// 引入Web3.js库
const Web3 = require('web3');

// 创建Web3实例,连接以太坊节点
const web3 = new Web3('https://mainnet.infura.io/v3/your-project-id');

// 创建交易对象
const txObject = {
    
    
    from: '0x1234567890123456789012345678901234567890',
    to: '0x0987654321098765432109876543210987654321',
    value: web3.utils.toWei('0.1', 'ether'),
};

// 签名并发送交易
web3.eth.accounts.signTransaction(txObject, 'your-private-key')
    .then(signedTx => {
    
    
        web3.eth.sendSignedTransaction(signedTx.rawTransaction)
            .then(receipt => {
    
    
                console.log(`交易哈希值:${
      
      receipt.transactionHash}`);
            })
            .catch(error => {
    
    
                console.error(error);
            });
    })
    .catch(error => {
    
    
        console.error(error);
    });

The above code creates a transaction object, including information such as the sender, receiver, and transfer amount. The transaction object is then signed using the private key and web3.eth.sendSignedTransaction()the transaction is sent via the method.

Interacting with smart contracts using Web3.js

Web3.js can also be used to interact with smart contracts, including calling contract methods and listening to contract events. Here is a sample code that uses Web3.js to call a smart contract method:

// 引入Web3.js库
const Web3 = require('web3');

// 创建Web3实例,连接以太坊节点
const web3 = new Web3('https://mainnet.infura.io/v3/your-project-id');

// 创建合约实例
const contract = new web3.eth.Contract(abi, contractAddress);

// 调用合约方法
contract.methods.balanceOf('0x1234567890123456789012345678901234567890').call()
    .then(balance => {
    
    
        console.log(`Token余额:${
      
      web3.utils.fromWei(balance, 'ether')} ETH`);
    })
    .catch(error => {
    
    
        console.error(error);
    });

The above code creates a contract instance and calls the contract balanceOf()method to query the Token balance of the specified account. Among them, abiis the ABI (Application Binary Interface) definition of the smart contract and contractAddressis the address of the smart contract.

Web3.js and Ethereum smart contracts to develop a simple DApp

A smart contract is required. We will create a very simple smart contract called SimpleStorage, which has a variable of type integer storedDataand two functions: setand get. setThe function will store an integer value into storedDatathe variable, and getthe function will return storedDatathe current value.

Below is the Solidity code for the smart contract:

pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

Next, we need to use Remix IDE (an online Solidity IDE) to compile the smart contract into bytecode and ABI (Application Binary Interface). Copy the compiled bytecode and ABI to a file, we will use them later.

Now, we need a Web3.js library. You can install it using the npm package manager. Enter the following command in the terminal:

npm install web3

Next, we need an Ethereum node to connect to. Here we will use the public node provided by Infura. You need to register an account on Infura, create a project, and obtain the project's API key. Copy the API key to a file, we will use it later.

Now, we can start writing JavaScript code. We will use Node.js to run this code. First, we need to import the Web3.js library and the ABI file we copied earlier. We also need to specify the URL of our Infura node and our account address. Here, we assume that you have created an Ethereum account and have the private key.

const Web3 = require('web3');
const contractABI = require('./SimpleStorageABI.json');

const infuraURL = 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';
const accountAddress = 'YOUR_ACCOUNT_ADDRESS';
const privateKey = 'YOUR_ACCOUNT_PRIVATE_KEY';

Next, we need to create an Ethereum network connection using Web3.js. We will use the public nodes provided by Infura to connect to the Ethereum mainnet. We also need to use our private key to unlock our account.

const web3 = new Web3(infuraURL);

const unlockAccount = async () => {
    
    
  try {
    
    
    await web3.eth.personal.unlockAccount(accountAddress, privateKey, 600);
    console.log('Account unlocked');
  } catch (error) {
    
    
    console.log(`Error unlocking account: ${
      
      error}`);
  }
};

unlockAccount();

Now that we have unlocked our account, we can use Web3.js to create a smart contract instance. We need to specify the address and ABI of the smart contract.

const contractAddress = 'CONTRACT_ADDRESS';

const simpleStorageContract = new web3.eth.Contract(
  contractABI,
  contractAddress
);

Next, we can use Web3.js to call getthe function of the smart contract to get storedDatathe value of the current variable.

const getData = async () => {
    
    
  try {
    
    
    const result = await simpleStorageContract.methods.get().call();
    console.log(`Stored data: ${
      
      result}`);
  } catch (error) {
    
    
    console.log(`Error getting data: ${
      
      error}`);
  }
};

getData();

We can also use Web3.js to call the smart contract's setfunction to store an integer value into storedDataa variable.

const setData = async (value) => {
    
    
  try {
    
    
    const gasPrice = await web3.eth.getGasPrice();
    const gasEstimate = await simpleStorageContract.methods
      .set(value)
      .estimateGas({
    
     from: accountAddress });
    const result = await simpleStorageContract.methods
      .set(value)
      .send({
    
     from: accountAddress, gas: gasEstimate, gasPrice: gasPrice });
    console.log(`Transaction hash: ${
      
      result.transactionHash}`);
  } catch (error) {
    
    
    console.log(`Error setting data: ${
      
      error}`);
  }
};

setData(42);

Now we can use Web3.js to interact with smart contracts. You can further explore the capabilities of Web3.js, such as how to use event listeners to listen for smart contract events. I hope this article can help you get started with Ethereum DApp development!

Guess you like

Origin blog.csdn.net/m0_69117588/article/details/130589006