一個Solidity智能合約

什么是合約?
在區塊鏈上運行的程序,通常稱為智能合約(Smart Contract)。所以通常會把寫區塊鏈程序改稱寫智能合約。

官方的solidity說明:
http://solidity.readthedocs.io/en/develop/

簡單點來講,合約就是運行在區塊鏈上的一段程序。

一個完整的合約

  pragma solidity ^0.4.4;

  contract Counter {

uint count = 0;
address owner;

function Counter() {
   owner = msg.sender;
} 

function increment() public {
   uint step = 10;
   if (owner == msg.sender) {
      count = count + step;
   }
}

function getCount() constant returns (uint) {
   return count;
}

function kill() {
   if (owner == msg.sender) { 
      selfdestruct(owner);
   }
}
    }

版本聲明
pragma solidity ^0.4.4;
pragma solidity代表solidity版本聲明,0.4.4代表solidity版本,表示向上兼容,0.4.4表示solidity的版本在0.4.4 ~ 0.5.0(不包含0.5.0)的版本都可以對上面的合約代碼進行編譯,0.4.5,0.4.8等等可以用來修復前面的solidity存在的一些bug。

合約聲明
contract是合約聲明的關鍵字,Counter是合約名字,contract Counter就是聲明一個Counter合約。

contract相當于其他語言中的class,Counter相當于類名。

狀態變量
uint count = 0;
address owner;
count和owner就是狀態變量,合約中的狀態變量相當于類中的屬性變量。

構造函數(Contructor)
function Counter()函數名和合約名相同時,此函數是合約的構造函數,當合約對象創建時,會先調用構造函數對相關數據進行初始化處理。

成員函數
function increment() public和function getCount() constant returns (uint)都是Counter合約的成員函數,成員函數在iOS里面叫做方法、行為,合約實例可以調用成員函數處理相關操作。當調用increment()函數時,會讓狀態變量count增加step。當調用getCount()時會得到狀態變量count的值。

本地變量
function increment() public {
uint step = 10;
if (owner == msg.sender) {
count = count + step;
}
}
increment()方法中聲明的step就是局部變量。局部變量只在離它最近的{}內容使用。

析構函數(selfdestruct)
析構函數和構造函數對應,構造函數是初始化數據,而析構函數是銷毀數據。在counter合約中,當我們手動調用kill函數時,就會調用selfdestruct(owner)銷毀當前合約。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。