Web3.ks

简介

Web3.js 是一个用于与以太坊区块链进行交互的 JavaScript 库。它为开发者提供了丰富的 API 来简化与以太坊节点的通信,从而方便地构建和部署去中心化应用(dApps)。Web3.js 支持多种操作,包括账户管理、智能合约交互、交易处理、事件订阅等。

核心功能

1. 连接以太坊节点

Web3.js 可以连接到不同类型的以太坊节点,包括本地节点、远程节点(例如 Infura 提供的节点)以及浏览器扩展(例如 MetaMask)。

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

2. 账户管理

Web3.js 提供了丰富的账户管理功能,可以生成新的账户、查询账户余额、解锁账户等。

// 获取账户列表
web3.eth.getAccounts().then(console.log);

// 创建新账户
const newAccount = web3.eth.accounts.create();
console.log(newAccount);

// 获取账户余额
web3.eth.getBalance('0xYourAccount').then(console.log);

3. 智能合约

Web3.js 允许你与智能合约进行交互,可以部署合约、调用合约方法、监听合约事件等。

const abi = [/* ABI array */];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(abi, contractAddress);

// 调用合约方法
contract.methods.yourMethod().call().then(console.log);

// 部署新合约
const newContract = new web3.eth.Contract(abi);
newContract.deploy({
    data: '0xYourContractBytecode'
}).send({
    from: '0xYourAccount',
    gas: 1500000,
    gasPrice: '30000000000000'
}).then(newContractInstance => {
    console.log(newContractInstance.options.address);
});

4. 交易处理

Web3.js 支持创建、签名和发送交易,可以处理普通交易和智能合约交易。

// 发送普通交易
web3.eth.sendTransaction({
    from: '0xYourAccount',
    to: '0xRecipientAccount',
    value: web3.utils.toWei('1', 'ether')
});

// 签名交易
const signedTransaction = web3.eth.accounts.signTransaction({
    to: '0xRecipientAccount',
    value: web3.utils.toWei('1', 'ether'),
    gas: 2000000
}, '0xYourPrivateKey');

web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).then(console.log);

5. 事件订阅

Web3.js 允许你订阅区块、交易、日志等事件,并在事件发生时触发回调。

// 订阅新块
web3.eth.subscribe('newBlockHeaders')
    .on('data', block => {
        console.log(block);
    })
    .on('error', console.error);

// 订阅合约事件
contract.events.YourEvent()
    .on('data', event => {
        console.log(event);
    })
    .on('error', console.error);

6. 工具函数

Web3.js 提供了一些实用工具函数,用于处理以太坊相关的常见任务,例如单位转换、哈希计算等。

// 单位转换
const valueInWei = web3.utils.toWei('1', 'ether');
const valueInEther = web3.utils.fromWei('1000000000000000000', 'ether');

// 计算哈希
const hash = web3.utils.sha3('Hello, Web3!');

总结

Web3.js 是一个功能强大的工具库,通过提供简洁易用的 API,使得与以太坊区块链的交互变得更加方便。无论是账户管理、智能合约操作还是交易处理,Web3.js 都能为开发者提供全面的支持,使他们能够专注于构建和优化去中心化应用。

基本使用方法

使用 Web3.js 进行以太坊区块链的开发通常涉及以下基本步骤:

  1. 安装 Web3.js
  2. 连接到以太坊节点
  3. 账户管理
  4. 智能合约交互
  5. 处理交易
  6. 订阅事件

下面是每个步骤的详细说明:

1. 安装 Web3.js

首先需要安装 Web3.js,可以通过 npm 或 yarn 进行安装:

npm install web3

或

yarn add web3

2. 连接到以太坊节点

创建一个 Web3 实例并连接到以太坊节点。可以连接到本地节点、远程节点(例如 Infura 提供的节点)或浏览器扩展(例如 MetaMask)。

const Web3 = require('web3');

// 连接到本地节点
const web3 = new Web3('http://localhost:8545');

// 连接到 Infura 提供的远程节点
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

// 连接到 MetaMask
const web3 = new Web3(window.ethereum);

3. 账户管理

Web3.js 提供了丰富的账户管理功能,包括生成新账户、查询账户余额等。

// 获取账户列表
web3.eth.getAccounts().then(accounts => {
  console.log(accounts);
});

// 创建新账户
const newAccount = web3.eth.accounts.create();
console.log(newAccount);

// 获取账户余额
web3.eth.getBalance('0xYourAccount').then(balance => {
  console.log(balance);
});

4. 智能合约交互

与智能合约进行交互,需要合约的 ABI 和合约地址。通过 Web3.js,可以调用合约的方法、发送交易和监听合约事件。

const abi = [/* ABI array */];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(abi, contractAddress);

// 调用合约方法
contract.methods.yourMethod().call().then(result => {
  console.log(result);
});

// 发送合约交易
contract.methods.yourMethod().send({
  from: '0xYourAccount'
}).then(receipt => {
  console.log(receipt);
});

5. 处理交易

可以使用 Web3.js 创建和发送交易,包括普通交易和智能合约交易。

// 发送普通交易
web3.eth.sendTransaction({
  from: '0xYourAccount',
  to: '0xRecipientAccount',
  value: web3.utils.toWei('1', 'ether')
}).then(receipt => {
  console.log(receipt);
});

// 签名并发送交易
const signedTransaction = web3.eth.accounts.signTransaction({
  to: '0xRecipientAccount',
  value: web3.utils.toWei('1', 'ether'),
  gas: 2000000
}, '0xYourPrivateKey');

web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).then(receipt => {
  console.log(receipt);
});

6. 订阅事件

Web3.js 允许订阅区块、交易、日志等事件,并在事件发生时触发回调。

// 订阅新块
web3.eth.subscribe('newBlockHeaders')
  .on('data', block => {
    console.log(block);
  })
  .on('error', console.error);

// 订阅合约事件
contract.events.YourEvent()
  .on('data', event => {
    console.log(event);
  })
  .on('error', console.error);

示例代码

下面是一个完整的示例代码,展示了如何使用 Web3.js 连接到 Infura 提供的以太坊节点,查询账户余额,并与智能合约交互。

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

// 获取账户列表
web3.eth.getAccounts().then(accounts => {
  console.log('Accounts:', accounts);

  // 获取第一个账户的余额
  web3.eth.getBalance(accounts[0]).then(balance => {
    console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'ETH');
  });
});

// 合约的 ABI 和地址
const abi = [/* ABI array */];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(abi, contractAddress);

// 调用合约方法
contract.methods.yourMethod().call().then(result => {
  console.log('Contract method result:', result);
});

// 发送合约交易
contract.methods.yourMethod().send({
  from: '0xYourAccount'
}).then(receipt => {
  console.log('Transaction receipt:', receipt);
});

以上是使用 Web3.js 的基本步骤,具体应用中可以根据实际需求进行调整和扩展。

Webjs 常用

以下是一些使用 Web3.js 的常用代码片段,涵盖了连接以太坊节点、账户管理、智能合约交互、交易处理和事件订阅等功能。

连接到以太坊节点

const Web3 = require('web3');

// 连接到本地节点
const web3 = new Web3('http://localhost:8545');

// 连接到 Infura 提供的远程节点
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

// 连接到 MetaMask
const web3 = new Web3(window.ethereum);

账户管理

// 获取账户列表
web3.eth.getAccounts().then(accounts => {
  console.log('Accounts:', accounts);
});

// 创建新账户
const newAccount = web3.eth.accounts.create();
console.log('New Account:', newAccount);

// 获取账户余额
const address = '0xYourAccount';
web3.eth.getBalance(address).then(balance => {
  console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'ETH');
});

// 解锁账户(仅适用于本地节点)
web3.eth.personal.unlockAccount('0xYourAccount', 'YourPassword', 600).then(success => {
  console.log('Account unlocked:', success);
});

智能合约交互

const abi = [/* ABI array */];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(abi, contractAddress);

// 调用合约方法
contract.methods.yourMethod().call().then(result => {
  console.log('Contract method result:', result);
});

// 发送合约交易
contract.methods.yourMethod().send({
  from: '0xYourAccount'
}).then(receipt => {
  console.log('Transaction receipt:', receipt);
});

// 部署新合约
const newContract = new web3.eth.Contract(abi);
newContract.deploy({
  data: '0xYourContractBytecode'
}).send({
  from: '0xYourAccount',
  gas: 1500000,
  gasPrice: '30000000000000'
}).then(newContractInstance => {
  console.log('New Contract Address:', newContractInstance.options.address);
});

交易处理

// 发送普通交易
web3.eth.sendTransaction({
  from: '0xYourAccount',
  to: '0xRecipientAccount',
  value: web3.utils.toWei('1', 'ether')
}).then(receipt => {
  console.log('Transaction receipt:', receipt);
});

// 签名并发送交易
const signedTransaction = web3.eth.accounts.signTransaction({
  to: '0xRecipientAccount',
  value: web3.utils.toWei('1', 'ether'),
  gas: 2000000
}, '0xYourPrivateKey');

signedTransaction.then(signedTx => {
  web3.eth.sendSignedTransaction(signedTx.rawTransaction).then(receipt => {
    console.log('Signed Transaction receipt:', receipt);
  });
});

事件订阅

// 订阅新块
web3.eth.subscribe('newBlockHeaders')
  .on('data', block => {
    console.log('New Block:', block);
  })
  .on('error', console.error);

// 订阅合约事件
contract.events.YourEvent()
  .on('data', event => {
    console.log('Event:', event);
  })
  .on('error', console.error);

// 取消订阅
const subscription = web3.eth.subscribe('newBlockHeaders');
subscription.unsubscribe((error, success) => {
  if (success) console.log('Successfully unsubscribed!');
});

工具函数

// 单位转换
const valueInWei = web3.utils.toWei('1', 'ether');
const valueInEther = web3.utils.fromWei('1000000000000000000', 'ether');
console.log('Value in Wei:', valueInWei);
console.log('Value in Ether:', valueInEther);

// 计算哈希
const hash = web3.utils.sha3('Hello, Web3!');
console.log('SHA3 Hash:', hash);

// 生成随机数
const randomHex = web3.utils.randomHex(32);
console.log('Random Hex:', randomHex);

完整示例

下面是一个完整的示例代码,展示了如何使用 Web3.js 连接到 Infura 提供的以太坊节点,查询账户余额,并与智能合约交互。

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

// 获取账户列表
web3.eth.getAccounts().then(accounts => {
  console.log('Accounts:', accounts);

  // 获取第一个账户的余额
  return web3.eth.getBalance(accounts[0]);
}).then(balance => {
  console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'ETH');
});

// 合约的 ABI 和地址
const abi = [/* ABI array */];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(abi, contractAddress);

// 调用合约方法
contract.methods.yourMethod().call().then(result => {
  console.log('Contract method result:', result);
});

// 发送合约交易
contract.methods.yourMethod().send({
  from: '0xYourAccount'
}).then(receipt => {
  console.log('Transaction receipt:', receipt);
});

// 订阅新块
web3.eth.subscribe('newBlockHeaders')
  .on('data', block => {
    console.log('New Block:', block);
  })
  .on('error', console.error);

这些代码片段涵盖了使用 Web3.js 的常见操作,可以根据具体需求进行调整和扩展。

简单的例子

好的,下面是更新后的示例,使用 Sepolia 测试网。

1. HTML 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web3.js Example</title>
    <script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js"></script>
    <script src="app.js" defer></script>
</head>
<body>
    <h1>Web3.js Example on Sepolia</h1>
    <button id="connectButton">Connect to MetaMask</button>
    <div id="accountInfo"></div>
    <div id="contractInfo"></div>
</body>
</html>

2. JavaScript 文件

更新 app.js 文件,以确保它使用 Sepolia 测试网。

// Ensure the document is fully loaded before executing the script
document.addEventListener('DOMContentLoaded', async () => {
    if (typeof window.ethereum !== 'undefined') {
        console.log('MetaMask is installed!');
    } else {
        console.log('MetaMask is not installed. Please install it to use this app.');
        return;
    }

    const connectButton = document.getElementById('connectButton');
    const accountInfo = document.getElementById('accountInfo');
    const contractInfo = document.getElementById('contractInfo');

    connectButton.addEventListener('click', async () => {
        // Request account access if needed
        await window.ethereum.request({ method: 'eth_requestAccounts' });

        // We have access to the user's accounts
        const web3 = new Web3(window.ethereum);

        // Check if connected to Sepolia Test Network (Chain ID: 11155111)
        const chainId = await web3.eth.getChainId();
        if (chainId !== 11155111) {
            alert('Please connect to the Sepolia Test Network');
            return;
        }

        const accounts = await web3.eth.getAccounts();
        const account = accounts[0];

        // Display account info
        const balance = await web3.eth.getBalance(account);
        const balanceInEther = web3.utils.fromWei(balance, 'ether');
        accountInfo.innerHTML = `
            <p>Account: ${account}</p>
            <p>Balance: ${balanceInEther} ETH</p>
        `;

        // Interact with a smart contract (example contract)
        const abi = [
            {
                "constant": false,
                "inputs": [
                    {
                        "name": "x",
                        "type": "uint256"
                    }
                ],
                "name": "set",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "get",
                "outputs": [
                    {
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }
        ];
        const contractAddress = '0xYourContractAddress'; // Replace with your contract address
        const contract = new web3.eth.Contract(abi, contractAddress);

        // Example: call a method from the contract
        const response = await contract.methods.get().call();
        contractInfo.innerHTML = `<p>Contract Response: ${response}</p>`;

        // Example: send a transaction to the contract
        const txResponse = await contract.methods.set(42).send({
            from: account
        });
        console.log('Transaction Response:', txResponse);
    });
});

3. Solidity 合约

这是一个简单的智能合约示例。如果你已经有一个智能合约,可以使用现有的合约。将这个合约部署到 Sepolia 测试网络。

创建一个名为 SimpleStorage.sol 的文件:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 public storedData;

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

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

部署智能合约

要部署智能合约,你可以使用 Remix IDE 或 Truffle。以下是使用 Remix IDE 部署的简单步骤:

  1. 打开 Remix IDE.
  2. 创建一个新的文件并粘贴上面的 Solidity 代码。
  3. 在 Solidity 编译器中编译合约。
  4. 在部署选项卡中,选择 “Injected Web3” 环境(确保你已连接到 Sepolia 测试网络)。
  5. 部署合约并记录合约地址。

运行示例

  1. 将 index.html 和 app.js 放在同一个目录下,并确保你已经替换了合约 ABI 和合约地址。
  2. 打开 index.html 文件,在浏览器中查看。
  3. 点击 “Connect to MetaMask” 按钮,连接到 MetaMask。
  4. 你应该能看到账户信息,并与合约进行交互。

这个示例展示了如何使用 Web3.js 连接到 MetaMask,查询账户余额,并与智能合约进行交互。可以根据需要进一步扩展和定制代码。

基本概念

在使用 MetaMask 和 Web3 开发以太坊应用时,以下是一些重要的概念:

  1. MetaMask(元掩码): MetaMask 是一个浏览器插件,允许用户在现代浏览器中与以太坊区块链交互。它充当了以太坊钱包,允许用户创建、管理以太坊账户、发送和接收以太币(ETH)、签署交易以及与智能合约交互。

  2. 以太坊网络: 以太坊是一个去中心化的开放源代码区块链平台,允许开发者构建和部署智能合约和分布式应用(DApp)。以太坊网络由全球节点网络支持,允许去中心化应用通过智能合约进行操作。

  3. Web3.js: Web3.js 是一个用于与以太坊节点通信的 JavaScript 库。它提供了一组 API,使开发者能够通过 JavaScript 与以太坊区块链进行交互,例如发送交易、查询账户余额、部署和调用智能合约等。

  4. 智能合约: 智能合约是在区块链上运行的自动化合约,其中包含了代码和数据。智能合约能够自动执行并确保在没有第三方干预的情况下执行。

  5. ABI(Application Binary Interface): ABI 是智能合约的接口定义,描述了合约的函数和参数。它允许外部应用程序与智能合约进行交互,通过指定函数名称、参数类型和返回类型。

  6. Gas 费用: 在以太坊网络上执行交易和调用智能合约需要支付 Gas 费用。Gas 是以太坊网络上的计算单位,每个操作和交易都需要一定量的 Gas 来执行。

  7. 去中心化应用(DApp): 去中心化应用是建立在区块链技术上的应用程序,它不依赖于传统的中心化服务和架构,通常使用智能合约来处理逻辑和数据存储。

  8. Nonce: 在以太坊交易中,Nonce 是一个递增的数字,用于确保每个交易的唯一性和顺序性。每个账户有自己的Nonce,用于标识其提交的交易顺序。

理解和掌握这些概念对于开发基于以太坊的去中心化应用(DApp)以及与 MetaMask 和 Web3.js 的交互至关重要。

总结

Web3.js 是一个用于与以太坊区块链进行交互的 JavaScript 库。它提供了一系列 API 来帮助开发者构建去中心化应用(dApps)。以下是 Web3.js 包含的主要内容和功能:

1. Web3 对象

Web3 对象是与以太坊节点通信的核心接口。通过创建 Web3 对象,可以与以太坊节点进行连接和交互。

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

2. Eth 模块

web3.eth 模块提供了与以太坊网络的交互功能,包括获取区块和交易信息、与智能合约交互等。

  • 获取账户

    web3.eth.getAccounts().then(console.log);
  • 获取区块信息

    web3.eth.getBlock('latest').then(console.log);
  • 发送交易

    web3.eth.sendTransaction({
        from: '0xYourAccount',
        to: '0xRecipientAccount',
        value: web3.utils.toWei('1', 'ether')
    });

3. Contract 模块

web3.eth.Contract 模块用于与智能合约进行交互。可以部署新合约或与现有合约进行通信。

  • 部署新合约

    const myContract = new web3.eth.Contract(abi);
    myContract.deploy({
        data: '0xContractBytecode'
    }).send({
        from: '0xYourAccount',
        gas: 1500000,
        gasPrice: '30000000000000'
    }).then((newContractInstance) => {
        console.log(newContractInstance.options.address);
    });
  • 与现有合约交互

    const myContract = new web3.eth.Contract(abi, contractAddress);
    myContract.methods.myMethod().call().then(console.log);

4. Utils 模块

web3.utils 模块提供了一些实用工具函数,用于处理以太坊相关的常见任务,例如单位转换、哈希计算等。

  • 单位转换

    const valueInWei = web3.utils.toWei('1', 'ether');
    const valueInEther = web3.utils.fromWei('1000000000000000000', 'ether');
  • 计算哈希

    const hash = web3.utils.sha3('Hello, Web3!');

5. Personal 模块

web3.eth.personal 模块用于账户管理,如创建新账户、解锁账户等。

  • 创建新账户

    web3.eth.personal.newAccount('password').then(console.log);
  • 解锁账户

    web3.eth.personal.unlockAccount('0xYourAccount', 'password', 600).then(console.log);

6. Net 模块

web3.eth.net 模块提供了网络相关的信息,如网络ID、连接状态等。

  • 获取网络ID

    web3.eth.net.getId().then(console.log);
  • 检查是否连接到网络

    web3.eth.net.isListening().then(console.log);

7. Shh 模块

web3.shh 模块用于 Whisper 协议,允许在以太坊节点之间进行加密消息传输。

  • 发送消息

    web3.shh.post({
        pubKey: '0xYourPublicKey',
        ttl: 10,
        topic: '0x12345678',
        payload: web3.utils.toHex('Hello Whisper'),
        powTime: 3,
        powTarget: 0.5
    }).then(console.log);

8. BZZ 模块

web3.bzz 模块用于与 Swarm 协议进行交互,Swarm 是以太坊的去中心化存储解决方案。

  • 上传文件

    web3.bzz.upload('Hello, Swarm').then(console.log);
  • 下载文件

    web3.bzz.download('bzz-raw://<hash>').then(console.log);

9. 订阅事件

Web3.js 允许你订阅区块、交易、日志等事件,并在事件发生时触发回调。

  • 订阅新块

    web3.eth.subscribe('newBlockHeaders')
      .on('data', block => {
          console.log(block);
      })
      .on('error', console.error);

10. 管理账号

可以使用 Web3.js 管理账号,包括创建新账号、解锁账号等。

  • 创建账号

    const account = web3.eth.accounts.create();
  • 解锁账号

    web3.eth.personal.unlockAccount('0xYourAccount', 'password', 600);

以上是 Web3.js 的主要内容和功能,通过掌握这些内容,你可以构建和管理去中心化应用,与以太坊区块链进行高效的交互。