iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 9
0
Blockchain

區塊鏈開發(Blockchain/DLT Application Development)系列 第 9

以太坊(Ethereum):Solidity

Solidity 是以太坊(Ethereum)指定用於智能合約開發的程式語言。
其語法類似於 JavaScript,擁有強型別、var 型別推論等特性。

開發環境建置

列出幾種常件的開發工具,比較推薦的是 browser-solidity,可以解決不同以太坊版本與 Solidity 之間差異問題。

基本架構

Solidity 基本由三個架構組成:

  • 狀態變數(State Variable):狀態機(State Machine)
  • 函式
    • 函式描述子(Function Modifier)
    • 建構式
    • 異動資料、呼叫其他合約
  • 事件:與鏈外互動:Web3.js

Hello world

contract HelloWorld 
{
    string public greeting = "";
    
    function setHelloWorld() 
    {
        greeting = "hello, world";
    }
}

資料型別

Solidity 為了結合智能合約帳戶及數位貨幣概念,設計了一些特殊型別,以便於進行如帳戶餘額的資料存取。

  • 實值型別
    • int / int256, uint
      uint constant HEX_NUM = 0x123A1;
      
    • address
      • 20 byte value 地址(address)的長度
    • bytesN (1 <= N <= 32)
      bytes32[5]	nicknames;	//靜態陣列
      bytes32[]	names;		//動態陣列
      names.length;			//陣列長度
      
  • 參考型別
    • Arrays:T 是數值型態
      T[]		t;	//動態長度陣列
      T[N]	t;	//N 長度陣列
      T[N][M]	t;	//M x N 陣列
      
    • Mappings
      //K, V 為泛型,其中 K 不可以為 Mapping 型別
      //當 K 不存在時,V 為 0
      //Ktype 為使用 SHA3 產生的哈希值
      mapping (Ktype => Vtype) myMap;	
      

地址(address):以哈希值作為為ㄧ的合約或帳戶代碼

  • 合約帳戶(Contract Account)
    address public owner;
    
  • 外部帳戶(External Account)
    • owner.balance
    mapping (string => uint) public balances;
    balances["Bob"] = 10 ether;
    

Structs 與 自訂型別

Structs 範例:

struct Bank 
{
    address owner;
    uint balance;
}

Bank bank = Bank
(
    {
        owner: "0x692a70d2e424a56d2c6c27aa97d1a86395877b3a"
        ,balance: 5
    }
);

自訂型別範例:使用 enums

enum Direction { Left, Right, Up, Down };
Direction myDirection = Direction.Up;

系統變數

  • block
    block.blockhash(uint blockNumber) returns (bytes32) 
    block.coinbase;  // 挖礦者的地址
    block.gaslimit;  // 現在區塊的 gas 限制
    block.number;    // 現在區塊的編號
    block.timestamp; // 現在區塊的時間,不等於確認(commit)時間
    
  • msg
    msg.sender;      // 訊息的發送者
    msg.value;       // 隨著訊息攜帶了多少貨幣 - wei
    
  • tx
    tx.origin;       // 交易的發送者
    
  • now
    block.timestamp; //等同於 block.timestamp
    

#### 流程控制

  • 邏輯
    • If、else、?:
  • 迴圈
    • while 、for 、break 、continue
  • 函式回傳
    return;
    return VALUE,..;
    function NAME(ARG,..) VISIBILITY returns (TYPE,...) {}
    

參考資源

Solidity 線上文件:https://solidity.readthedocs.io


上一篇
以太坊(Ethereum):交易與區塊
下一篇
以太坊(Ethereum):智能合約
系列文
區塊鏈開發(Blockchain/DLT Application Development)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言