1. 工具介紹
我們需要用到的工具
- Truffle:是以太坊的開發環境、測試框架和資產通道。換句話說,它可以幫助你開發、發佈和測試智能合約等等。
- Ganache:以前叫作 TestRPC,如果你讀過幾個月前的教程的話,有可能他們在使用 TestRPC 的情境下配合使用了 Truffle,它在 TestRPC 和 Truffle 的集成後被重新命名爲 Ganache。Ganache 的工作很簡單:創建一個虛擬的以太坊區塊鏈,並生成一些我們將在開發過程中用到的虛擬賬號。
2 環境安裝
我是在本地 mac 安裝測試所需的所有環境。
root 權限 NPM 全局安裝(-g)仍會權限不夠,添加參數 --unsafe-perm
安裝 truffle
sudo npm install -g truffle --unsafe-perm
安裝 ganache-cli
sudo npm install -g ganache-cli --unsafe-perm
接下來我們要配置環境,
# 創建一個智能合約工程腳手架
mkdir hello
cd hello
truffle init
創建之後代碼結構如下
hello
|-contracts
|-migrations
|-test
|_truffle-config.js
當使用開發網絡時,使用端口7545,連接到127.0.0.1(localhost)的主機。配置 truffle-config.js 文件
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
}
啓動 ganache,Ganache會爲我們生成測試賬戶,默認情況下,每個賬戶都有未鎖定的100個以太幣並,所以我們可以自由地從那裏發送以太幣。後面truffle 的所有交互都是在此條本地測試私鏈上進行。
ganache-cli -p 7545
3 第一個智能合約 Hello World
contracts 目錄下編寫 Hello.sol 智能合約代碼
pragma solidity ^0.5.16;
contract Hello {
constructor() public {
}
function print() public pure returns(string memory) {
return "Hello World";
}
function add(uint n1, uint n2) public pure returns(uint) {
return n1 + n2;
}
}
test 目錄下編寫單元測試代碼 TestHello.sol
pragma solidity ^0.5.16;
import "../contracts/Hello.sol";
import "truffle/Assert.sol";
contract TestHello {
function testAdd() public {
Hello hello = new Hello();
uint result = hello.add(1, 20);
Assert.equal(result, 21, "TestAdd");
}
function testPrint() public {
Hello hello = new Hello();
string memory result = hello.print();
Assert.equal(result, "Hello World", "TestPrint");
}
}
migrations目錄下新建3_deploy_hello.js文件
var Hello = artifacts.require("./Hello.sol");
module.exports = function(deployer) {
deployer.deploy(Hello);
};
測試
# 測試
truffle test
# 編譯
truffle compile
# 部署合約
# Migrate(遷移) 會把代碼部署到區塊鏈,我們之前在 “truffle-config.js” 文件中設置了 “development” 網絡,我們可以在那裏找到區塊鏈。
truffle migrate --network development
部署成功後顯示了交易id和合約地址。
# 進入 truffle 控制檯
truffle console --network development
與合約交互操作,可以看看運行命令後的效果
Hello.address
HelloInst.print();
HelloInst.add(10, 200);
至此 我們第一個 HelloWorld 智能合約的開發、測試、本地測試鏈上的部署以及交互就完成了。