WEB頁面訪問以太坊智慧合約--使用Web3
準備工作
-
使用remix IDE開發智慧合約程式碼,並部署合約到測試鏈上。請參考《使用remix釋出智慧合約》
-
安裝Ganache,使用Ganache模擬一個以太坊坊節點。請參考《Ganache模擬以太坊區塊鏈節點》
Web3簡介
Web3JS是以太坊官方的Javascript API庫的集合,通過web3可以開發出使用者友好的去中心化應用,Web3與以太坊節點通訊實現了 JSON-RPC協議 ,這是一種輕量級的RPC(Remote Procedure Call)協議,整個通訊的模型可以抽象為下圖。
安裝Web3
安裝web3之前,需要先安裝nodejs和npm,如果不知道怎麼安裝的可以參考《使用ganche模擬以太坊節點》,裡邊有介紹到。進入nodejs命令列終端,輸入下面命令,建立web3userinfo專案,我們把專案放在e盤,當然也可以放到其它位置上:
D:\ProgramFiles\blockchain\nodejs>e: E:\>mkdir web3useinfo E:\>cd web3useinfo
然後,使用 node.js 的包管理工具 npm 初始化專案:
E:\web3useinfo>npm init
下來一路回車完成package.json檔案的建立,這個檔案用來定義專案基本資訊包括專案名稱,版本,作者等。接下來,使用下面的命令來安裝web3js:
E:\web3useinfo>npm install [email protected]^0.20.0
以節點模組的方式引入web3,所以安裝完成後專案檔案裡多了一個node_modules檔案,資料夾裡邊就是web3相關的js函式庫。
注意:“npm install [email protected]
建立介面
在專案目錄下建立index.html,在這裡我們將建立前端介面,功能包括姓名和年齡的輸入框,以及一個按鈕,這些將通過 jQuery 實現:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="./node_modules/web3/dist/web3.min.js"></script><!—引入web3-->
</head>
<body>
<div class="container">
<h1>使用者資訊智慧合約</h1>
<h2 id="info"></h2>
<label for="name" class="col-lg-2 control-label">姓名</label>
<input id="name" type="text">
<label for="name" class="col-lg-2 control-label">年齡</label>
<input id="age" type="text">
<button id="button">更新資訊</button>
</div>
<script src="./node_modules/ jquery-3.2.1/jquery-3.2.1.slim.min.js"></script>
<script src=”./app/index.js”>
// 引入更新和讀取智慧合約的程式碼
</script>
</body>
</html>
接下來需要編寫main.css檔案設定基本的樣式:
body {
background-color:#F0F0F0;
padding: 2em;
font-family: 'Raleway','Source Sans Pro', 'Arial';
}
.container {
width: 50%;
margin: 0 auto;
}
label {
display:block;
margin-bottom:10px;
}
input {
padding:10px;
width: 50%;
margin-bottom: 1em;
}
button {
margin: 2em 0;
padding: 1em 4em;
display:block;
}
#instructor {
padding:1em;
background-color:#fff;
margin: 1em 0;
}
到此頁面已經準備好了。
編寫互動的程式碼
使用Web3與智慧合約互動,在專案根目錄下新建檔案./app/index.js,修改html頁面的<script src=”./app/index.js”></scrip>指令碼,引入互動的程式碼。
可以開始編寫在index.js程式碼,首先建立web3例項,並連線我們的GANACHE以太坊節點:
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider); //可以用來連線metamask Provider
} else {
// 建立新的provider,連線本地以太坊節點,我們可以連線ganache作為模擬節點
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}
上面程式碼作用是如果web3已經被定義,那麼就可以直接當作我們的provider 使用。如果沒有定義,則我們手動指定 provider。
在上面程式碼的基礎上,接下來設定預設的以太坊賬戶:
web3.eth.defaultAccount = web3.eth.accounts[0];
Ganache安裝完成後,預設自動建立了 10 個賬戶了提供給我們使用,這裡我們選擇第一個賬戶當作預設賬戶。
接下來需要獲取合約的 ABI(Application Binary Interface)和合約地址,簡單來說,合約地址是用來區分不同合約的,而ABI是用來定義合約擁有什麼的功能。只有知道了合約的地址和ABI才可以和合約進行互動。假設已經發布了UserInfoContract合約,並獲取到ABI後,把ABI貼上到下面方法裡。
var userInfoContract = web3.eth.contract(貼上合約ABI);
如果沒有釋出UserInfoContract合約,可以參考《使用remix釋出智慧合約》。接下來拷貝合約的地址,將其複製到下面的程式碼中:
var userInfo = userInfoContract.at('貼上合約地址');
完成這些我們就可以呼叫合約中的函數了,下面使用 jQuery 與我們的合約進行互動:
serInfo.getUser(function(error, result){
if(!error)
{
$("#info").html(result[0]+' ('+result[1]+' 歲 )');
console.log(result);
}
else
console.error(error);
});
$("#button").click(function() {
info.setUser($("#name").val(), $("#age").val());
});
以上的程式碼就簡單地實現了對合約中兩個函式的呼叫,分別讀取和顯示姓名(userName)和年齡(userAge)變數。
到此我們就完成了全部的程式碼, index.html測試效果如下圖(輸入名字和年齡後重新整理)。
總結一下,通過這一課程,介紹了使用web3js,web頁面和智慧合約進行互動。
參考文獻
-
Interacting with a Smart Contract through Web3.js :
(Tutorial)) https://coursetro.com/posts/code/99/Interacting-with-a-Smart-Contract-through-Web3.js-(Tutorial