智能合約簡介 Move on Aptos

作者:師大科技系 PecuLab 蔡芸琤 (Pecu)

這篇是介紹 Aptos 公鏈上,如何透過 Move 實現智能合約。若對智能合約沒有概念的讀者,可先 Google 一下智能合約,就會跑出一大堆基本介紹。

https://www.youtube.com/c/KryptoCamp/videos 上也有許介紹 Ethereum 公鏈上,如何透過 Solidity 實現智能合約的影片。

那假設各位讀者們,可類比 Aptos 公鏈上的智能合約使用 Move (原生語言為 Rust) 開發,之於 Ethereum 公鏈上的智能合約使用 Solidity 開發的概念。

來開始介紹 Move on Aptos 的幾個基本重要關鍵概念 https://aptos.dev/guides/move-guides/move-on-aptos

  1. 除非明確說明,否則會要求signer(這個就是會呼叫使用者進行簽署確認的意思,例如:像在使用 MetaMask,某些合約需要進行使用者確認時,錢包會跳出要使用者簽章的畫面) 限制對帳戶添加或刪除資產的存取。
  2. 資料 (Data) 是存在資料自己的帳戶中,而不是發布這筆資料的使用者的帳戶中,這是非常有趣的關鍵概念,把資料擬人化。
  3. 因為資料自己是屬於自己的帳戶 (好繞口,你的資料不是你的資料),所以就需要有個對應使用者與資料之間的關係 indexing works,使得資料流 (Data Flow) 的對應如下圖所示:

https://aptos.dev/guides/indexing/

有了這樣的觀念後,就可以參考 https://github.com/aptos-labs/move/blob/main/language/documentation/tutorial/README.md#Step1 來了解,如何透過 Move 來撰寫 Aptos 上的智能合約。

從範例 https://github.com/aptos-labs/move/blob/main/language/documentation/tutorial/step_1/BasicCoin/sources/FirstModule.move 解釋,程式碼使用說明,可參考 https://move-language.github.io/move/modules-and-scripts.html

module 0xCAFE::BasicCoin {
    struct Coin has key {
        value: u64,
    }

    public fun mint(account: signer, value: u64) {
        move_to(&account, Coin { value })
    }
}
module <address>::<identifier> {
    (<use> | <friend> | <type> | <function> | <constant>)*
}

其中可對應出,當要發布合約時,可指定此合約要放在哪個地址中 module <address>::<identifier> (地址配上合約名稱),接著就可以寫合約內容。

在合約中的最開始,會定義此合約使用到的公用變數、資料結構,接著就定義合約要執行的功能 (Functions),以這個最簡單的範例來看。要定義合約中的資料結構特性 (Type),可參考 https://move-language.github.io/move/abilities.html

struct Coin has key {
        value: u64,
    }

以範例程式中提及的資料結構,使用的 Type 為 Key。

當給予相對應的特性,就會依照該特性可運作的範圍來管理這個資料結構。

public fun mint(account: signer, value: u64) {
        move_to(&account, Coin { value })
    }
fun <identifier><[type_parameters: constraint],*>([identifier: type],*): <return_type> <acquires [identifier],*> <function_body>

https://move-language.github.io/move/functions.html

其中可對應出,此合約的唯一功能是 mint,當執行 mint 時,就會呼叫 Move 中的 move_to,將 mint 的此合約的代幣轉入簽署人的錢包中。

https://move-book.com/resources/resource-by-example/storing-new-resource.html

本文是想要提供讀者一個自學文件的閱讀脈絡,以及了解整個合約框架的宣告及定義,接下來會帶著讀者們閱讀更多不同的 Move 合約,請持續追蹤。