Photo by Debbie Pan / Unsplash

Background

俗話說的好 畢圈一日 人間一年..... 開始學 Smart Contract吧.

Installation

$ npm install -g truffle

Set Developing Environment

下載 ganache 來協助我們取得到一個開發用的Ethereum節點. (here)

P.S Ganache is available for Windows, Mac and Linux

Init

$ mkdir hello_world
$ cd helle_world
$ truffle init
$ tree
.
├── build
│   └── contracts
│       └── Migrations.json
├── contracts
│   └── Migrations.sol
├── migrations
│   └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js

First Smart Contract

$ cd contracts
$ truffle create contract HelloWorld

HelloWorld.sol

pragma solidity ^0.4.11;

contract HelloWorld {
    function sayHello() public returns (string) {
        return ("Hello World");
    }
}
$ truffle compile

編譯成功的話,在build/contracts/目錄下會多出HelloWorld.json這個檔案.

$ tree
.
├── build
│   └── contracts
│       ├── HelloWorld.json
│       └── Migrations.json
├── contracts
│   ├── HelloWorld.sol
│   └── Migrations.sol
├── migrations
│   └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js

Migration

truffle框架中提供了方便部署合約的腳本。我們可以在migrations/目錄下維護這些腳本. 這些腳本除了能部署合約,也可以用來遷移合約中的資料.

$ cd migrations
$ vim 2_deploy_contracts.js

2_deploy_contracts.js

var HelloWorld = artifacts.require("HelloWorld");

module.exports = function(deployer) {
  deployer.deploy(HelloWorld);
};

Network Setting

接著要跟剛剛安裝的開發node做連結. 首先打開 Ganache, 打開後會如下圖:

Screen-Shot-2018-07-21-at-9.53.16-PM

有10組已經準備好的錢包. 然後上面有一欄資訊欄. 有 RPC server, Network id. 把這下資訊填入下方程式對應的欄位.

$ vim truffle.js

truffle.js

...

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "5777"
    }
  }
};

Deploy

$ truffle migrate
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xd06589f00111a6a5ebe69b7b4aa8dbff5ce772c673deadf6f57d74359c4d6060
  Migrations: 0x76ee5867f55d8e9df4f0e437b63a10bff955329a
Saving successful migration to network...
  ... 0x1cefb50f7606696714020bdfb24665ece62f23fa9dfe387eca155ba6d68c0e04
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying HelloWorld...
  ... 0xe04df66a9ea3d7ff5865d49e0fb4a18d6f9dc77cc84f46afc83f7898a0181a1e
  HelloWorld: 0x8d151cbc7f5637f0c17097bba531636fb9973ef4
Saving successful migration to network...
  ... 0x18c885354c40d82ae85592060910fcc39c65a958083231fe848f37838d183178
Saving artifacts...

可以看到 Ganache 有發生變化.

Screen-Shot-2018-07-21-at-10.39.08-PM

Screen-Shot-2018-07-21-at-10.39.13-PM

Interaction

$ truffle console
$ truffle(development)> HelloWorld
...
...
...
# 可以看到一堆關於這個 Contract 的資訊
...
...
# 接著呼叫我們剛剛創立的程式
truffle(development)> HelloWorld.at("0x8d151cbc7f5637f0c17097bba531636fb9973ef4").sayHello.call()
'Hello World'

# 離開command line 介面
$ truffle(development)> .exit

以上就是一個簡單智能合約的範例.

Reference