以太坊系列 -

时间:2025-03-26 15:22:56

是一组用来和本地或远程以太坊节点进行交互的js库,它可以使用HTTP或IPC建立与以太坊节点旳连接。
底层实现上,它通过RPC 调用与本地或远程节点通信。可以与任何暴露了RPC接口的以太坊节点连接。

Installation

npm install web3

Usage

// In 
const Web3 = require('web3');

let web3 = new Web3('ws://localhost:8546');
console.log(web3);
> {
    eth: ... ,
    shh: ... ,
    utils: ...,
    ...
}

0. 与 版本的区别

这是 主要的两类版本

  • truffle migratetruffle test 时会用操作系统安装的web3js版本,可以用truffle verson查看
  • nodejs会使用中指定的web3js版本号

版本的变动

  • if ('utils' in web3) 可用此判断web3j的版本
  • web3.sha3.sha3 取代
    • 要哈希的数据在调用.sha3 前需要先判空: if (!input || !) { return; }
  • is deprecated. Use () instead
  • 取代
  • 取代
  • watch不再支持.
    • ([params]).watch([callback])([params],[callback]) 取代
  • The HTTP provider is deprecated, as it won’t work for subscriptions.得改用websocket
    • websockets: true
    • HttpProvider 被 WebsocketProvider 取代, 端口号不用变
    • network_local.json 中的 rpcUrl 配置成 ws://127.0.0.1:9545

老的项目想通过编译

# 中配置
"web3": "^0.20.0",

# npm时
npm install --force

往期精彩回顾:
区块链知识系列
密码学系列
零知识证明系列
共识系列
公链调研系列
比特币系列
以太坊系列
EOS系列
Filecoin系列
联盟链系列
Fabric系列
智能合约系列
Token系列