區塊鏈 14 | 自製一個以太坊私有鏈(三)
使用Web3.js取得以太坊私有鏈上的資料、部署智能合約
Published in
7 min readMay 12, 2021
web3.js 是Ethereum 開發的JavaScript API
要運行web3.js的話用node最方便,所以先來建置一個簡單的node 專案
Desktop$ mkdir web3_projectDesktop$ cd web3_projectDesktop web3_project$ npm init
在專案中安裝web3.js模組
$ npm install web3 --save
在專案根目錄直接新增一個 index.js檔案,填入下列 code:
const Web3 = require('web3');// connect to ethereum nodeconst ethereumUri = 'http://localhost:8545'; // port 預設8545,可以另行設定const web3 = new Web3(ethereumUri);// 取得帳戶資訊
web3.eth.getAccounts().then(console.log);
執行index.js
$ node index.js
如果有返回一串0x開頭的數值像這樣:
['0xD452eC5f19669c220c2be79Fa0Cf69427dC3dbB7']
表示與私有鏈連結成功!
其他web3.js 的方法
- 取得現在區塊數,回傳區塊號碼(int)
web3.eth.getBlockNumber().then(console.log);>2744
- 取得某一帳戶的餘額,回傳餘額(int)
web3.eth.getBalance("0xD452eC5f19669c220c2be79Fa0Cf69427dC3dbB7").then(console.log);>"1000000000000"
- 取得某一區塊資訊: 需帶入 “區塊號碼” 或是 “區塊hash值”,回傳區塊資訊(object)
web3.eth.getBlock(2744).then(console.log);>{"number": 2744,"hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46","parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88","nonce": "0xfb6e1a62d119228b","sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","transactionsRoot": "0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee","stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb","miner": "0x8888f1f195afa192cfee860698584c030f4c9db1","difficulty": "21345678965432","totalDifficulty": "324567845321","size": 616,"extraData": "0x","gasLimit": 3141592,"gasUsed": 21662,"timestamp": 1429287689,"transactions": ["0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"],"uncles": []}
- 解鎖帳戶(unlock account)
web3.eth.personal.unlockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!", 600).then(console.log("Account unlocked!"));
接下來學習如何使用Web3.js部署智能合約
使用Web3.js部署智能合約
- 編譯智能合約,取得編譯好的合約json檔
** 智能合約的編譯是使用truffle 框架另外做的,以下是一個簡單的智能合約範例:
pragma solidity ^0.5.16;contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() view public returns (uint) {
return storedData;
}
}
2. 在剛剛的node專案中(index.js),引入編譯好的智能合約(json)檔案
const json = require(“contracts/SimpleStorage.json”);
3. 部署合約
// 建立新合約的Interface
const myContract = new web3.eth.Contract(json.abi)// 部署合約
myContract.deploy({
data: json.bytecode
})
.send({
from: accounts[0],
gas: 1500000,
gasPrice: '30000000000000'
})
.then(function(newContractInstance){
contAddress = newContractInstance.options.address
console.log(newContractInstance.options.address)
// instance with the new contract address
});
如果回傳合約地址表示成功將合約部署上鏈了!
呼叫智能合約的方法修改資料
// 首先要找到那張智能合約,一樣要先建立一個新的合約的Interfaceconst myContract = new web3.eth.Contract(json.abi, contAddress, {from: accounts[0]})
// 呼叫方法: 修改鏈上資料的result = myContract.methods.set(123456789).send({from: accounts[0]})
// 呼叫方法: 取出鏈上資料result1 = await myContract.methods.get().call();console.log('result1 '+ result1) // 123456789
參考
- 查看完整程式碼【github web3js blockchain】