蜜桃av色欲a片精品一区,麻豆aⅴ精品无码一区二区,亚洲人成网站在线播放影院在线,亚洲 素人 字幕 在线 最新

微立頂科技

新聞資訊

創(chuàng)新 服務(wù) 價(jià)值

  什么是 Web3.js - Web3.js 庫簡介

發(fā)布日期:2022/10/4 23:31:37      瀏覽量:

文章概述

  1. 1. 什么是 web3.js?
  2. 2. Web3.js 與 ethers.js。
  3. 3. 如何在 web3.js 中運(yùn)行 JavaScript 代碼。
  4. 4. web3.js 是做什么用的?

事不宜遲,讓我們深入web3.js的世界;讓我們徹底了解它的含義以及如何在我們的智能合約[1]程序中實(shí)現(xiàn)它。

什么是 Web3.js?

Web3.js[2]是一個(gè)庫集合,允許您使用 HTTP、IPC 或 WebSocket 與本地或遠(yuǎn)程以太坊節(jié)點(diǎn)進(jìn)行交互。

Web3.js允許您開發(fā)與區(qū)塊鏈交互的網(wǎng)站或客戶端。例如,它允許您將以太幣從一個(gè)賬戶發(fā)送到另一個(gè)賬戶、從智能合約讀取和寫入數(shù)據(jù)、創(chuàng)建智能合約等等!

以下文檔將指導(dǎo)您安裝和運(yùn)行 web3.js[3],并提供帶有示例的 API 參考文檔。

使用以太坊開發(fā)區(qū)塊鏈應(yīng)用程序有幾個(gè)不同的方面:

  • ? 智能合約開發(fā)——使用 Solidity 編程語言編寫部署到區(qū)塊鏈的代碼。
  • ? 開發(fā)與區(qū)塊鏈交互的網(wǎng)站或客戶端——編寫代碼,通過智能合約從區(qū)塊鏈讀取和寫入數(shù)據(jù)。

如果您有 Web 開發(fā)背景,您可能已經(jīng)使用 jQuery 對 Web 服務(wù)器進(jìn)行 Ajax 調(diào)用。這是理解web3.js功能的一個(gè)很好的起點(diǎn)。您可以使用web3.js來讀取和寫入以太坊區(qū)塊鏈,而不是使用 jQuery 從 Web 服務(wù)器讀取和寫入數(shù)據(jù)。

下圖說明了web3.js如何與以太坊區(qū)塊鏈交互:


Web3.js 與 ethers.js

web3.js和ethers.js都是以太坊 JavaScript 庫。

Ether.js由加拿大開發(fā)人員 Rick Moore 開發(fā)和維護(hù)。

Web3.js由以太坊基金會開發(fā)和維護(hù)。因此,對web3.js有更廣泛的支持,因?yàn)橛懈嗟拈_發(fā)人員支持它。

ethers.jsweb3.js之間的一個(gè)主要區(qū)別是它們?nèi)绾翁幚砻荑€管理以及與以太坊區(qū)塊鏈的交互。

Web3.js假設(shè)有一個(gè)本地節(jié)點(diǎn)連接到應(yīng)用程序。假設(shè)節(jié)點(diǎn)存儲密鑰、簽署交易、讀取以太坊區(qū)塊鏈并與之交互。實(shí)際上,這種情況并不常見——大多數(shù)用戶并沒有在本地運(yùn)行g(shù)eth 。[5]Metamask 通過瀏覽器應(yīng)用程序有效地模擬了該環(huán)境,因此大多數(shù) web3 應(yīng)用程序都需要 Metamask 來保存密鑰、簽署交易并與以太坊主[6]網(wǎng)交互。

另一方面,**ethers.js[7]采用了一種不同的方法,我們認(rèn)為這為開發(fā)人員提供了更大的靈活性。Ethers.js**將“節(jié)點(diǎn)”分成兩個(gè)不同的角色:

  • ? 一個(gè)保存密鑰和簽署交易的“錢包”,以及
  • ? 充當(dāng)與以太坊網(wǎng)絡(luò)的匿名連接、檢查狀態(tài)和發(fā)送交易的“提供者”。

想到的ethers.js的兩個(gè)主要優(yōu)點(diǎn)是:

  1. 1. ENS 名字是一等公民。
  2. 2. 密鑰管理和狀態(tài) - 關(guān)注點(diǎn)分離。
如何在 Web3.js 中運(yùn)行 JavaScript 代碼

要在web3.js中運(yùn)行 Javascript 代碼,您需要將web3.js放入您的項(xiàng)目中。這可以使用以下方法完成:

依賴項(xiàng)

有一些依賴項(xiàng)可以幫助您開始使用web3.js進(jìn)行開發(fā)。

節(jié)點(diǎn)包管理器 (NPM)

我們需要的第一個(gè)依賴項(xiàng)是Node.js 附帶的Node Package Manager或 NPM。[8]要檢查您是否已經(jīng)安裝了 Node,請轉(zhuǎn)到您的終端并輸入:

node -vWeb3.js 庫

您可以在終端中使用 NPM 安裝 Web3.js 庫,如下所示:

npm install web3

或使用yarn:

yarn add web3Infura rpc URL

要在主網(wǎng)上使用 JSON RPC 連接到以太坊節(jié)點(diǎn),我們需要訪問以太坊節(jié)點(diǎn)。有幾種方法可以做到這一點(diǎn)。

你可以做到這一點(diǎn)的一種方法是使用Geth[9]或Parity 運(yùn)行你自己的以太坊節(jié)點(diǎn)。[10]但這需要你從區(qū)塊鏈下載大量數(shù)據(jù)并保持同步。如果您以前從未嘗試過這樣做,這將是一個(gè)巨大的頭痛。

主要是為了方便,您可以使用Infura[11]訪問以太坊節(jié)點(diǎn),而無需自己運(yùn)行。Infura 是一項(xiàng)免費(fèi)提供遠(yuǎn)程以太坊節(jié)點(diǎn)的服務(wù)。您需要做的就是注冊,并為您想要連接的網(wǎng)絡(luò)獲取 API 密鑰和 RPC URL。注冊后,您的 Infura RPC URL 應(yīng)如下所示:

https://mainnet.infura.io/YOUR_INFURA_API_KEYweb3.js 是做什么用的?

Web3.js可用于前端和后端檢查賬戶余額、從區(qū)塊鏈讀取數(shù)據(jù)、進(jìn)行交易,甚至部署智能合約。

1. 使用 web3.js 查看賬戶余額

現(xiàn)在您的所有依賴項(xiàng)都已安裝,讓我們來看看如何使用 web3.js 檢查您的帳戶余額。首先,您應(yīng)該像這樣在終端中啟動 Node 控制臺:

node

現(xiàn)在您已經(jīng)打開了 Node 控制臺!在 Node 控制臺中,您可以像這樣要求 web3.js:

const Web3 = require(’web3’);

現(xiàn)在,您可以訪問一個(gè)變量,您可以在其中創(chuàng)建一個(gè)新的 web3 連接。在我們生成 web3 連接之前,我們必須首先將 Infura URL 分配給一個(gè)變量,如下所示:

const rpcURL = "https://mainnet.infura.io/YOUR_INFURA_API_KEY";

確保將YOUR_INFURA_API_KEY“替換為您之前獲得的實(shí)際 Infura API 密鑰?,F(xiàn)在您可以像這樣實(shí)例化 Web3 連接:

const web3 = new Web3(rpcURL);

現(xiàn)在,你有一個(gè)實(shí)時(shí)的 web3 連接,可以讓你與以太坊主網(wǎng)對話。讓我們使用這個(gè)連接來檢查這個(gè)賬戶的賬戶余額:0x105cb19ba40384a8f2985816DA7883b076969cA7。我們可以通過web3.eth.getBalance()查看其余額來查看該帳戶持有多少以太幣。

第一步,讓我們將地址分配給一個(gè)變量:

const address = "0x105cb19ba40384a8f2985816DA7883b076969cA7";

現(xiàn)在讓我們像這樣檢查帳戶余額:

web3.eth.getBalance(address, (err, wei) => {balance = web3.utils.fromWei(wei, ’ether’)

就是這樣!這就是您使用web3.js檢查帳戶余額的方式。

以下是我們在本教程中編寫的代碼的摘要:

const Web3 = require(’web3’)const rpcURL = ’’ // Your RPC URL goes hereconst web3 = new Web3(rpcURL)const address = ’’ // Your account address goes hereweb3.eth.getBalance(address, (err, wei) => {balance = web3.utils.fromWei(wei, ’ether’)

首先,我們通過調(diào)用web3.eth.getBalance()來檢查余額,它接受一個(gè)帶有兩個(gè)參數(shù)的回調(diào)函數(shù),error和balance自身。我們現(xiàn)在將忽略該error參數(shù),并使用該wei參數(shù)引用余額。以太坊以 wei 表示余額,這是 ether 的最小細(xì)分,有點(diǎn)像一分錢。我們可以用web3.utils.fromWei(wei, ’ether’); 將這個(gè)余額轉(zhuǎn)換為以太幣。

2.用web3.js從智能合約中讀取數(shù)據(jù)

在本節(jié)中,我們將簡要學(xué)習(xí)如何從以太坊區(qū)塊鏈中讀取智能合約數(shù)據(jù)。

為了使用 web3.js 從智能合約中讀取數(shù)據(jù),我們需要兩件事:

  1. 1. 我們想要與之交互的智能合約的 JavaScript 表示。
  2. 2. 讀取數(shù)據(jù)時(shí)調(diào)用智能合約上的函數(shù)的一種方式。

我們可以通過web3.eth.Contract()函數(shù)獲得以太坊智能合約的 JavaScript 表示。

該函數(shù)需要兩個(gè)參數(shù):一個(gè)用于智能合約 ABI,一個(gè)用于智能合約地址。

智能合約 ABI 代表“抽象二進(jìn)制接口”,它是一個(gè) JSON 數(shù)組,描述了特定智能合約的工作方式。

下面是一個(gè) ABI 示例:

const abi = [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"Function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"},{"name":"_releaseTime","type":"uint256"}],"name":"mintTimelocked","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]

我知道這似乎是一個(gè)非常長的、完整的陣列。如果它看起來有壓迫性,請不要擔(dān)心。這個(gè)例子是 OmiseGo 代幣的 ABI,它實(shí)現(xiàn)了 ERC-20 代幣標(biāo)準(zhǔn)。您可以在Etherscan[12]上找到有關(guān)此令牌的更多詳細(xì)信息,包括其 ABI 和地址。我們將在其余示例中使用此智能合約 ABI。

當(dāng)我們在這里時(shí),我將繼續(xù)從以太坊主網(wǎng)將地址存儲到 OMG 令牌:

const address = "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07";

現(xiàn)在我們已經(jīng)分配了這兩個(gè)值,我們可以像這樣創(chuàng)建 OMG 代幣智能合約的完整 JavaScript 表示:

const contract = new web3.eth.Contract(abi, address);

現(xiàn)在本文的第一部分已經(jīng)完成,我們需要完成第二部分:通過調(diào)用其函數(shù)從智能合約中讀取數(shù)據(jù)。所有智能合約功能都列在contract.methods分配的 Web3 合約的命名空間下。例如,contract.methods.myFunction()如果合約實(shí)現(xiàn)了,我們可以調(diào)用myFunction().

偉大的!所以理論上我們可以調(diào)用智能合約實(shí)現(xiàn)的任何功能。但是我們怎么知道它實(shí)現(xiàn)了哪些功能呢?一方面,我們可以打印contract.methods到控制臺,看看返回了什么。然而,由于這個(gè)智能合約實(shí)現(xiàn)了 ERC-20 標(biāo)準(zhǔn),我們知道它實(shí)現(xiàn)了幾個(gè)功能,如totalSupply()、name()、symbol()和balanceOf()。我們可以單獨(dú)讀取每個(gè)值,如下所示:

首先,現(xiàn)有的所有 OMG 代幣的總供應(yīng)量:

contract.methods.totalSupply().call((err, result) => { console.log(result) });// > 140245398

二、OMG代幣名稱:

contract.methods.name().call((err, result) => { console.log(result) });// > OMG Token

最后,我們可以檢查給定帳戶的余額。我在 Etherscan 上尋找了一個(gè) OMG 持有者,并找到了這個(gè)地址“ 0xd26114cd6EE289AccF82350c8d8487fedB8A0C07”。

我們可以像這樣檢查這個(gè)帳戶的余額:

contract.methods.balanceOf(’0xd26114cd6EE289AccF82350c8d8487fedB8A0C07’).call((err, result) => { console.log(result) });// > Some large number...

就是這樣!這就是您使用web3.js從智能合約中讀取數(shù)據(jù)的方式。

以下是本節(jié)所有代碼的摘要:

const Web3 = require(’web3’);const rpcURL = ’’ // Your RCP URL goes here const web3 = new Web3(rpcURL)const web3 = new Web3(rpcURL);const abi = [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"},{"name":"_releaseTime","type":"uint256"}],"name":"mintTimelocked","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]const address = ’0xd26114cd6EE289AccF82350c8d8487fedB8A0C07’ ;const contract = new web3.eth.Contract(abi, address);contract.methods.totalSupply().call((err, result) => { console.log(result) });contract.methods.name().call((err, result) => { console.log(result) });contract.methods.symbol().call((err, result) => { console.log(result) });contract.methods.balanceOf(’0xd26114cd6EE289AccF82350c8d8487fedB8A0C07’).call((err, result) =>{ console.log(result) }); // > Some large number...3. 使用 web3.js 創(chuàng)建以太坊交易

本節(jié)將向您展示如何使用web3.js在以太坊區(qū)塊鏈上創(chuàng)建交易。您將看到創(chuàng)建以太坊交易時(shí)會發(fā)生什么,以及如何使用web3.js將交易手動廣播到網(wǎng)絡(luò)。

除了學(xué)習(xí)web3.js 之外,本文的目的是幫助您了解交易在以太坊區(qū)塊鏈上的基本原理。每當(dāng)您創(chuàng)建交易時(shí),您就是在將數(shù)據(jù)寫入?yún)^(qū)塊鏈并更新其狀態(tài)。有幾種方法可以做到這一點(diǎn),比如將以太幣從一個(gè)賬戶發(fā)送到另一個(gè)賬戶,調(diào)用寫入數(shù)據(jù)的智能合約函數(shù),以及將智能合約部署到區(qū)塊鏈。通過使用 web3.js 庫執(zhí)行這些操作并觀察每個(gè)步驟的工作方式,我們可以更好地理解這些概念。

為了向網(wǎng)絡(luò)廣播交易,我們需要先對它們進(jìn)行簽名。我將使用一個(gè)名為ethereumjs-tx[13]的附加 JavaScript 庫來執(zhí)行此操作。您可以像這樣從命令行安裝此依賴項(xiàng):

npm install ethereumjs-tx

我們要使用這個(gè)庫的原因是我們想在本地簽署所有交易。如果我們在本地運(yùn)行自己的以太坊節(jié)點(diǎn),我們可以解鎖本地存儲的帳戶并在本地簽署我們的所有交易。如果是這樣的話,我們不一定需要使用這個(gè)庫。但是,在本教程中,我們使用的是 Infura 托管的遠(yuǎn)程節(jié)點(diǎn)。雖然 Infura 是一項(xiàng)值得信賴的服務(wù),但我們?nèi)匀幌M诒镜睾炇鸾灰祝皇亲屵h(yuǎn)程節(jié)點(diǎn)管理我們的私鑰。

這正是我們將在本文中所做的。我們將創(chuàng)建原始交易,對其進(jìn)行簽名,然后發(fā)送交易并將其廣播到網(wǎng)絡(luò)。

讓我們首先創(chuàng)建一個(gè)簡單的index.js文件來運(yùn)行本課中的代碼,而不是在控制臺中執(zhí)行所有操作。

在index.js文件中,我們首先需要新安裝的庫,如下所示:

const Tx = require(’ethereumjs-tx’)

接下來,我們將設(shè)置一個(gè) web3 連接,就像我們在上一節(jié)中所做的那樣:

const Web3 = require(’web3’)const web3 = new Web3(’https://ropsten.infura.io/YOUR_INFURA_API_KEY’)

請注意,我們使用的是 Ropsten 測試網(wǎng)絡(luò),這與我們在上一節(jié)中使用的以太坊主網(wǎng)不同。我們將使用測試網(wǎng)絡(luò),因?yàn)樗薪灰锥家砸蕴珟诺男问较臍怏w。我們可以在 Ropsten 測試網(wǎng)上使用假以太幣,而不用擔(dān)心花錢。您可以從Ropsten 測試網(wǎng)絡(luò)[14]上的水龍頭或Metamask 水龍頭[15]獲得假以太幣。

我們將創(chuàng)建一個(gè)交易,將假以太幣從一個(gè)賬戶發(fā)送到另一個(gè)賬戶。為此,我們需要兩個(gè)帳戶及其私鑰。

您實(shí)際上可以像這樣使用 web3.js 創(chuàng)建新帳戶:

web3.eth.accounts.create()// address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",// privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",// signTransaction: function(tx){...},// sign: function(data){...},// encrypt: function(password){...}

創(chuàng)建這兩個(gè)帳戶后,請確保使用水龍頭中的假以太幣加載它們?,F(xiàn)在,我們將他們的公鑰分配給我們腳本中的變量,如下所示:

const account1 = ’0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01’;const account2 = ’0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa02’;

注意:請務(wù)必使用您生成的帳戶,因?yàn)檫@些帳戶不適用于本課程?,F(xiàn)在,讓我們將私鑰保存到環(huán)境中,如下所示:

const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1);const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_2);

我們現(xiàn)在已經(jīng)設(shè)置了所有變量。我知道在這一點(diǎn)上,其中一些可能有點(diǎn)令人困惑。堅(jiān)持我,這一切很快就會變得有意義。

從這一點(diǎn)來說,我們想做幾件事:

  1. 1. 構(gòu)建交易對象。
  2. 2. 簽署交易。
  3. 3. 將交易廣播到網(wǎng)絡(luò)。

我們可以像這樣構(gòu)建事務(wù)對象:

const txObject = {nonce: web3.utils.toHex(txCount),to: account2,value: web3.utils.toHex(web3.utils.toWei(’0.1’, ’ether’)),gasLimit: web3.utils.toHex(21000),gasPrice: web3.utils.toHex(web3.utils.toWei(’10’, ’gwei’))

在此代碼中,我們正在構(gòu)建一個(gè)對象,該對象具有生成事務(wù)所需的所有值,例如nonce、to、value、gasLimit和gasPrice。

讓我們分解每個(gè)值:

  • ? nonce- 這是給定帳戶的先前交易計(jì)數(shù)。我們將立即分配此變量的值。我們還必須將此值轉(zhuǎn)換為十六進(jìn)制。我們可以使用 web3.js 實(shí)用程序來做到這一點(diǎn)web3.utils.toHex()。
  • ? to- 我們發(fā)送以太幣的賬戶。
  • ? value- 我們要發(fā)送的以太幣數(shù)量。此值必須以 wei 表示并轉(zhuǎn)換為十六進(jìn)制。我們可以使用 web3.js 實(shí)用程序?qū)⒅缔D(zhuǎn)換為 wei web3.utils.toWei()。
  • ? gasLimit- 這是交易消耗的最大氣體量。像這樣的基本交易總是需要 21000 單位的 gas,所以我們將在這里使用它來計(jì)算價(jià)值。
  • ? gasPrice- 這是我們要為每單位 gas 支付的金額。我將在這里使用 10 Gwei。

請注意,此交易對象中沒有表單字段。每當(dāng)我們使用account1的私鑰簽署此交易時(shí),就會推斷出這一點(diǎn)。

現(xiàn)在讓我們?yōu)?nonce 變量賦值。我們可以通過web3.eth.getTransactionCount()函數(shù)獲取交易nonce。我們將把所有代碼包裝在一個(gè)回調(diào)函數(shù)中,如下所示:

web3.eth.getTransactionCount(account1, (err, txCount) => {const txObject = {nonce: web3.utils.toHex(txCount),to: account2,value: web3.utils.toHex(web3.utils.toWei(’0.1’, ’ether’)),gasLimit: web3.utils.toHex(21000),gasPrice: web3.utils.toHex(web3.utils.toWei(’10’, ’gwei’))

像這樣,我們已經(jīng)完成了事務(wù)對象的構(gòu)建!現(xiàn)在我們要進(jìn)行sign交易了。我們可以這樣做:

const tx = new Tx(txObject)tx.sign(privateKey1)const serializedTx = tx.serialize()const raw = ’0x’ + serializedTx.toString(’hex’)

這里我們使用etheremjs-tx庫創(chuàng)建了一個(gè)新的“ Tx object”。我們也使用這個(gè)庫來用“privateKey1”簽署交易。接下來,我們將事務(wù)序列化并將其轉(zhuǎn)換為十六進(jìn)制字符串,以便可以將其傳遞給 web3。最后,我們將這個(gè)簽名的序列化交易發(fā)送到測試網(wǎng)絡(luò),web3.eth.sendSignedTransaction()函數(shù)如下:

web3.eth.sendSignedTransaction(raw, (err, txHash) => {console.log(’txHash:’, txHash)

這是本課的最后一步,發(fā)送交易并將其廣播到網(wǎng)絡(luò)。此時(shí),您完成的index.js文件應(yīng)如下所示:

var Tx = require(’ethereumjs-tx’)const Web3 = require(’web3’)const web3 = new Web3(’https://ropsten.infura.io/YOUR_INFURA_API_KEY’)const account1 = ’’ // Your account address 1const account2 = ’’ // Your account address 2const privateKey1 = Buffer.from(’YOUR_PRIVATE_KEY_1’, ’hex’)const privateKey2 = Buffer.from(’YOUR_PRIVATE_KEY_2’, ’hex’)web3.eth.getTransactionCount(account1, (err, txCount) => {// Build the transactionconst txObject = {nonce: web3.utils.toHex(txCount),to: account2,value: web3.utils.toHex(web3.utils.toWei(’0.1’, ’ether’)),gasLimit: web3.utils.toHex(21000),gasPrice: web3.utils.toHex(web3.utils.toWei(’10’, ’gwei’))// Sign the transactionconst tx = new Tx(txObject)tx.sign(privateKey1)const serializedTx = tx.serialize()const raw = ’0x’ + serializedTx.toString(’hex’)// Broadcast the transactionweb3.eth.sendSignedTransaction(raw, (err, txHash) => {console.log(’txHash:’, txHash)// Now go check etherscan to see the transaction!

然后,您可以使用 NodeJS 從終端運(yùn)行該index.js文件,如下所示:

node index.js

或者簡單地運(yùn)行:

node indexWeb3.js 實(shí)用程序

關(guān)于 web3.js,有一些你可能不知道的很酷的提示和技巧。讓我們繼續(xù)設(shè)置index.js并開始看看這些技巧。讓我們像這樣連接到以太坊主網(wǎng):

const Web3 = require(’web3’)const web3 = new Web3(’https://mainnet.infura.io/YOUR_INFURA_API_KEY’)

首先,您實(shí)際上可以獲得網(wǎng)絡(luò)當(dāng)前的平均汽油價(jià)格,如下所示:

web3.eth.getGasPrice().then((result) => {console.log(web3.utils.fromWei(result, ’ether’)

假設(shè)您以前在區(qū)塊鏈上進(jìn)行過開發(fā),您可能已經(jīng)處理過散列函數(shù)。Web3.js 有很多用于使用散列函數(shù)的內(nèi)置助手。

您可以像這樣直接訪問該sha3函數(shù):

console.log(web3.utils.sha3(’Hashnode blog’));

或keccack256:

console.log(web3.utils.keccak256(’Hashnode blog’));

您還可以通過生成 32 字節(jié)隨機(jī)十六進(jìn)制來處理(偽)隨機(jī)性,如下所示:

console.log(web3.utils.randomHex(32));

無論如何,您是否曾經(jīng)發(fā)現(xiàn)自己試圖對 JavaScript 數(shù)組或?qū)ο髨?zhí)行操作,并且需要外部庫的幫助?值得慶幸的是,web3.js 附帶 underscoreJS 庫:

const _ = web3.utils.__.each({ key1: ’value1’, key2: ’value2’ }, (value, key) => {console.log(key)

就是這樣!這些是您可以與web3.js 一起使用的一些花哨的提示和技巧。這是本課的完整教程代碼:

const Web3 = require(’web3’)const web3 = new Web3(’https://mainnet.infura.io/YOUR_INFURA_API_KEY’)// Get average gas price in wei from last few blocks median gas priceweb3.eth.getGasPrice().then((result) => {console.log(web3.utils.fromWei(result, ’ether’)// Use sha256 Hashing functionconsole.log(web3.utils.sha3(’Hashnode blog’))// Use keccak256 Hashing function (alias)console.log(web3.utils.keccak256(’Dapp University’))// Get a Random Hexconsole.log(web3.utils.randomHex(32))// Get access to the underscore JS libraryconst _ = web3.utils.__.each({ key1: ’value1’, key2: ’value2’ }, (value, key) => {console.log(key)

現(xiàn)在您可以使用 NodeJS 從終端運(yùn)行index.js文件,如下所示:

node index.js

或者簡單地運(yùn)行:

node index結(jié)論

在本文中,我們了解了 web3.js 庫的全部內(nèi)容。我們介紹了web3.jsethers.js,它們的區(qū)別以及它們的用途。

我們還學(xué)習(xí)了如何使用web3.js檢查賬戶余額、從智能合約中讀取數(shù)據(jù),以及如何使用web3.js創(chuàng)建以太坊交易。

我們還簡要了解了一些web3.js提示和技巧。

引用鏈接

[1] 智能合約: https://web3.hashnode.com/glossary/what-are-smart-contracts
[2] Web3.js: https://web3js.readthedocs.io/en/v1.5.2/index.html
[3] 安裝和運(yùn)行 web3.js: https://web3js.readthedocs.io/en/v1.5.2/getting-started.html#adding-web3
[4] iotbl: https://iotbl.blogspot.com/2017/03/ethereum-and-blockchain-2.html
[5] geth 。: https://geth.ethereum.org/
[6] 坊主: https://web3.hashnode.com/glossary/what-is-mainnet
[7] ethers.js: https://docs.ethers.io/v5/
[8] Node Package Manager或 NPM。: https://nodejs.org/en/
[9] Geth: https://github.com/ethereum/go-ethereum/wiki/geth
[10] Parity 運(yùn)行你自己的以太坊節(jié)點(diǎn)。: https://www.parity.io/
[11] Infura: https://infura.io/
[12] 您可以在Etherscan: https://etherscan.io/address/0xd26114cd6EE289AccF82350c8d8487fedB8A0C07
[13] ethereumjs-tx: https://github.com/ethereumjs/ethereumjs-tx
[14] 您可以從Ropsten 測試網(wǎng)絡(luò): http://faucet.ropsten.be:3001/
[15] Metamask 水龍頭: https://faucet.metamask.io/



  業(yè)務(wù)實(shí)施流程

需求調(diào)研 →

團(tuán)隊(duì)組建和動員 →

數(shù)據(jù)初始化 →

調(diào)試完善 →

解決方案和選型 →

硬件網(wǎng)絡(luò)部署 →

系統(tǒng)部署試運(yùn)行 →

系統(tǒng)正式上線 →

合作協(xié)議

系統(tǒng)開發(fā)/整合

制作文檔和員工培訓(xùn)

售后服務(wù)

馬上咨詢: 如果您有業(yè)務(wù)方面的問題或者需求,歡迎您咨詢!我們帶來的不僅僅是技術(shù),還有行業(yè)經(jīng)驗(yàn)積累。
QQ: 39764417/308460098     Phone: 13 9800 1 9844 / 135 6887 9550     聯(lián)系人:石先生/雷先生