• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

web3.js的使用,从连接metamask到回调事件

武飞扬头像
一个月只能改一次欧
帮助1

web3.js 库是一组包含以太坊生态系统功能的模块。

  • web3-eth :用于以太坊区块链和智能合约。
  • web3-shh:用于whisper 协议,用于p2p 和广播通信。
  • web3-bzz:用于swarm协议,去中心化文件存储。
  • web3-utils:包含对 Dapp 开发人员有用的帮助函数。

使用web3.js

1、首先,下载web3.js

分别有一下几种方法:

npm:npm install web3 yarn: yarn add web3 bower: bower install web3 meteor: meteor add ethereum:web3 pure js: link the dist/web3.min.js vanilla: link dist/web3.min.js

2、创建一个 web3 实例并设置一个provider.

<1>、大多数支持以太坊的浏览器(如 MetaMask钱包)都有一个符合EIP-1193的提供程序在 window.ethereum

<2>、检查Web3.givenProvider.如果此属性是null您应该连接到远程/本地节点。 一般使用if语句 const web3 = new Web3(Web3.givenProvider || "ws://localhost:8545"); 如果是node.js,则要引入模板: const Web3 = require('web3');

例如: 1、 if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { // 设置你想要的web3.providers web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } 2、

js // 检查是否是新的 MetaMask 或 DApp 浏览器 var web3Provider; if (window.ethereum) { web3Provider = window.ethereum; try { // 请求用户授权 await window.ethereum.enable(); } catch (error) { // 用户不授权时 console.error("User denied account access") } } else if (window.web3) { // 老版 MetaMask Legacy dapp browsers... web3Provider = window.web3.currentProvider; } else { web3Provider = new Web3.providers.HttpProvider('http://localhost:8545'); } web3 = new Web3(web3Provider); 这样就可以开始使用了。。。

Callbacks Promises Events(回调承诺事件)

web3集成到具有不同标准的各种项目中,提供了多种方式来处理异步函数。大多数 web3.js 对象都允许回调作为最后一个参数,以及返回对链function的promises

web3.eth.sendTransaction为了满足这一要求,我们为类似或合约方法的函数返回一个“promiEvent”

PromiEvents 的工作方式与添加了on,onceoff功能的普通 Promise 类似。通过这种方式,开发人员可以监视其他事件

```js

web3.eth.sendTransaction({ from: '0x123...', data: '0x432...' }) .once('sending', function(payload){ ... }) .once('sent', function(payload){ ... }) .once('transactionHash', function(hash){ ... }) .once('receipt', function(receipt){ ... }) .on('confirmation', function(confNumber, receipt, latestBlockHash){ ... }) .on('error', function(error){ ... }) .then(function(receipt){ // will be fired once the receipt is mined });

```

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgacfgj
系列文章
更多 icon
同类精品
更多 icon
继续加载