教學課程:在 Azure 區塊鏈服務上建立、建置和部署智慧型合約Tutorial: Create, build, and deploy smart contracts on Azure Blockchain Service

在本教學課程中,在 Visual Studio Code 中使用適用於 Ethereum 的 Azure 區塊鏈開發套件擴充功能,在 Azure 區塊鏈服務上建立、建置及部署智慧型合約。In this tutorial, use the Azure Blockchain Development Kit for Ethereum extension in Visual Studio Code to create, build, and deploy a smart contract on Azure Blockchain Service. 您也可使用開發套件以透過交易執行智慧型合約函式。You also use the development kit to execute a smart contract function via a transaction.

您可以使用適用於 Ethereum 的 Azure 區塊鏈服務開發套件來:You use Azure Blockchain Development Kit for Ethereum to:

  • 建立智慧型合約Create a smart contract
  • 部署智慧型合約Deploy a smart contract
  • 透過交易執行智慧型合約函式Execute a smart contract function via a transaction

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

PrerequisitesPrerequisites

在 Windows 上,node-gyp 模組需要已安裝的 C++ 編譯器。On Windows, an installed C++ compiler is required for the node-gyp module. 您可以使用 MSBuild 工具:You can use the MSBuild tools:

  • 如果已安裝 Visual Studio 2017,請將 npm 設定為使用 MSBuild 工具搭配 npm config set msvs_version 2017 -g 命令If Visual Studio 2017 is installed, configure npm to use the MSBuild tools with the command npm config set msvs_version 2017 -g
  • 如果已安裝 Visual Studio 2019,請設定 npm 的 MSBuild 工具路徑。If Visual Studio 2019 is installed, set the MS build tools path for npm. 例如, npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe"For example, npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe"
  • 否則,請在提升權限的「以系統管理員身分執行」 命令殼層中,使用 npm install --global windows-build-tools 來安裝獨立的 VS Build 工具。Otherwise, install the stand-alone VS Build tools using npm install --global windows-build-tools in an elevated Run as administrator command shell.

如需 node-gyp 的詳細資訊,請參閱 GitHub 上的 node-gyp 存放庫For more information about node-gyp, see the node-gyp repository on GitHub.

建立智慧型合約Create a smart contract

適用於 Ethereum 的 Azure 區塊鏈服務開發套件會使用專案範本和 Truffle 工具來協助進行合約的 Scaffold、建置及部署。The Azure Blockchain Development Kit for Ethereum uses project templates and Truffle tools to help scaffold, build, and deploy contracts. 開始之前,請完成先決條件快速入門:使用 Visual Studio Code 連線至聯盟網路Before you begin, complete the prerequisite Quickstart: Use Visual Studio Code to connect to a Azure Blockchain Service consortium network. 本快速入門引導您進行適用於 Ethereum 的 Azure 區塊鏈開發套件安裝和設定。The quickstart guides you through the installation and configuration of the Azure Blockchain Development Kit for Ethereum.

  1. 從 VS Code 命令選擇區選擇 [區塊鏈服務:新增 Solidity 專案]。From the VS Code command palette, choose Blockchain: New Solidity Project.
  2. 選擇 [建立基本專案]。Choose Create basic project.
  3. 建立名為 HelloBlockchain 的新資料夾,然後 選取新的專案路徑Create a new folder named HelloBlockchain and Select new project path.

Azure 區塊鏈服務開發套件會為您建立並初始化新的 Solidity 專案。The Azure Blockchain Development Kit creates and initializes a new Solidity project for you. 基本專案包含 HelloBlockchain 智慧型合約範例,以及要在 Azure 區塊鏈服務中對聯盟成員建置及部署的所有必要檔案。The basic project includes a sample HelloBlockchain smart contract and all the necessary files to build and deploy to your consortium member in Azure Blockchain Service. 可能需要數分鐘的時間才能建立好專案。It may take several minutes for the project to be created. 您可以選取 Azure 區塊鏈服務的輸出,以在 VS Code 的終端機面板中監視進度。You can monitor the progress in VS Code's terminal panel by selecting the output for Azure Blockchain.

專案結構看起來會像下列範例:The project structure looks like the following example:

Solidity 專案

建置智慧型合約Build a smart contract

智慧型合約位於專案的 [合約] 目錄中。Smart contracts are located in the project's contracts directory. 您必須先編譯智慧型合約才能將其部署至區塊鏈。You compile smart contracts before you deploy them to a blockchain. 請使用 [組建合約] 命令來編譯專案中的所有智慧型合約。Use the Build Contracts command to compile all the smart contracts in your project.

  1. 在 VS Code 總管的提要欄位中,展開專案中的 [合約] 資料夾。In the VS Code explorer sidebar, expand the contracts folder in your project.

  2. 對 [HelloBlockchain.sol] 按一下滑鼠右鍵,然後從功能表中選擇 [建置合約]。Right-click HelloBlockchain.sol and choose Build Contracts from the menu.

    選擇 [建置合約] 功能表Choose Build contracts menu

Azure 區塊鏈服務開發套件會使用 Truffle 來編譯智慧型合約。Azure Blockchain Development Kit uses Truffle to compile the smart contracts.

Truffle 編譯器輸出

部署智慧型合約Deploy a smart contract

Truffle 會使用移轉指令碼將合約部署至 Ethereum 網路。Truffle uses migration scripts to deploy your contracts to an Ethereum network. 移轉項目是位於專案 [移轉] 目錄中的 JavaScript 檔案。Migrations are JavaScript files located in the project's migrations directory.

  1. 若要部署智慧型合約,請對 [HelloBlockchain.sol] 按一下滑鼠右鍵,然後從功能表中選擇 [部署合約]。To deploy your smart contract, right-click HelloBlockchain.sol and choose Deploy Contracts from the menu.
  2. 請在命令選擇區中選擇您的 Azure 區塊鏈聯盟網路。Choose your Azure Blockchain consortium network in the command palette. 當您建立專案時,系統會在專案的 Truffle 設定檔中新增聯盟區塊鏈網路。The consortium blockchain network was added to the project's Truffle configuration file when you created the project.
  3. 選擇 [產生助憶檔]。Choose Generate mnemonic. 選擇檔案名稱,並將助憶檔案儲存在專案資料夾中。Choose a filename and save the mnemonic file in the project folder. 例如: myblockchainmember.envFor example, myblockchainmember.env. 助憶檔案可用來為區塊鏈成員產生 Ethereum 私密金鑰。The mnemonic file is used to generate an Ethereum private key for your blockchain member.

Azure 區塊鏈服務開發套件會使用 Truffle 來執行移轉指令碼,以將合約部署至區塊鏈。Azure Blockchain Development Kit uses Truffle to execute the migration script to deploy the contracts to the blockchain.

已成功部署的合約

<a name="call-a-contract-function">呼叫合約函式Call a contract function

HelloBlockchain 合約的 SendRequest 函式會變更 RequestMessage 狀態變數。The HelloBlockchain contract's SendRequest function changes the RequestMessage state variable. 區塊鏈網路狀態的變更會透過交易來完成。Changing the state of a blockchain network is done via a transaction. 您可以建立指令碼來透過交易執行 SendRequest 函式。You can create a script to execute the SendRequest function via a transaction.

  1. 在 Truffle 專案的根目錄中建立新的檔案,並將其命名為 sendrequest.jsCreate a new file in the root of your Truffle project and name it sendrequest.js. 在該檔案中新增下列 Web3 JavaScript 程式碼。Add the following Web3 JavaScript code to the file.

    var HelloBlockchain = artifacts.require(&quot;HelloBlockchain");
    
    module.exports = function(done) {
      console.log("Getting the deployed version of the HelloBlockchain smart contract")
      HelloBlockchain.deployed().then(function(instance) {
        console.log("Calling SendRequest function for contract ", instance.address);
        return instance.SendRequest("Hello, blockchain!");
      }).then(function(result) {
        console.log("Transaction hash: ", result.tx);
        console.log("Request complete");
        done();
      }).catch(function(e) {
        console.log(e);
        done();
      });
    };
    
  2. 當 Azure 區塊鏈服務開發套件建立專案時,系統會使用聯盟區塊鏈網路端點的詳細資料來產生 Truffle 設定檔。When Azure Blockchain Development Kit creates a project, the Truffle configuration file is generated with your consortium blockchain network endpoint details. 在專案中開啟 truffle-config.jsOpen truffle-config.js in your project. 設定檔會列出兩個網路:一個命名為「開發」,一個則具有和聯盟相同的名稱。The configuration file lists two networks: one named development and one with the same name as the consortium.

  3. 在 VS Code 的終端機窗格中,使用 Truffle 在聯盟區塊鏈網路上執行指令碼。In VS Code's terminal pane, use Truffle to execute the script on your consortium blockchain network. 在終端機窗格的功能表列中,於下拉式清單內選取 [終端機] 索引標籤和 [PowerShell]。In the terminal pane menu bar, select the Terminal tab and PowerShell in the dropdown.

    truffle exec sendrequest.js --network <blockchain network>
    

    <blockchain network>以 truffle-config.js 中定義之區塊鏈網路的名稱取代。Replace <blockchain network> with the name of the blockchain network defined in the truffle-config.js.

Truffle 就會在區塊鏈網路上執行指令碼。Truffle executes the script on your blockchain network.

顯示交易已傳送的輸出

當您透過交易執行合約的函式時,系統要等到建立區塊後才會處理交易。When you execute a contract's function via a transaction, the transaction isn't processed until a block is created. 應該會透過交易來執行的函式會傳回交易識別碼,而非傳回值。Functions meant to be executed via a transaction return a transaction ID instead of a return value.

查詢合約狀態Query contract state

智慧型合約函式可以傳回狀態變數的目前值。Smart contract functions can return the current value of state variables. 讓我們新增函式以傳回狀態變數的值。Let's add a function to return the value of a state variable.

  1. 在 [HelloBlockchain.sol] 中,將 getMessage 函式新增至 HelloBlockchain 智慧型合約。In HelloBlockchain.sol, add a getMessage function to the HelloBlockchain smart contract.

    function getMessage() public view returns (string memory)
    {
        if (State == StateType.Request)
            return RequestMessage;
        else
            return ResponseMessage;
    }
    

    函式會根據合約的目前狀態,傳回狀態變數中所儲存的訊息。The function returns the message stored in a state variable based on the current state of the contract.

  2. 以滑鼠右鍵按一下 [HelloBlockchain.sol],然後從功能表中選擇 [建置合約] 來編譯智慧型合約的變更。Right-click HelloBlockchain.sol and choose Build Contracts from the menu to compile the changes to the smart contract.

  3. 若要部署,請對 [HelloBlockchain.sol] 按一下滑鼠右鍵,然後從功能表中選擇 [部署合約]。To deploy, right-click HelloBlockchain.sol and choose Deploy Contracts from the menu. 出現提示時,請在命令選擇區中選擇您的 Azure 區塊鏈聯盟網路。When prompted, choose your Azure Blockchain consortium network in the command palette.

  4. 接下來,使用 getMessage 函式的呼叫來建立指令碼。Next, create a script using to call the getMessage function. 在 Truffle 專案的根目錄中建立新的檔案,並將其命名為 getmessage.jsCreate a new file in the root of your Truffle project and name it getmessage.js. 在該檔案中新增下列 Web3 JavaScript 程式碼。Add the following Web3 JavaScript code to the file.

    var HelloBlockchain = artifacts.require("HelloBlockchain");
    
    module.exports = function(done) {
      console.log("Getting the deployed version of the HelloBlockchain smart contract")
      HelloBlockchain.deployed().then(function(instance) {
        console.log("Calling getMessage function for contract ", instance.address);
        return instance.getMessage();
      }).then(function(result) {
        console.log("Request message value: ", result);
        console.log("Request complete");
        done();
      }).catch(function(e) {
        console.log(e);
        done();
      });
    };
    
  5. 在 VS Code 的終端機窗格中,使用 Truffle 在區塊鏈網路上執行指令碼。In VS Code's terminal pane, use Truffle to execute the script on your blockchain network. 在終端機窗格的功能表列中,於下拉式清單內選取 [終端機] 索引標籤和 [PowerShell]。In the terminal pane menu bar, select the Terminal tab and PowerShell in the dropdown.

    truffle exec getmessage.js --network <blockchain network>
    

    <blockchain network>以 truffle-config.js 中定義之區塊鏈網路的名稱取代。Replace <blockchain network> with the name of the blockchain network defined in the truffle-config.js.

指令碼會藉由呼叫 getMessage 函式來查詢智慧型合約。The script queries the smart contract by calling the getMessage function. 系統會傳回 RequestMessage 狀態變數的目前值。The current value of the RequestMessage state variable is returned.

Getmessage 查詢的輸出,顯示 RequestMessage 狀態變數的目前值

請注意,此值不是 Hello, blockchain!Notice the value is not Hello, blockchain!. 相反地,所傳回的值是預留位置。Instead, the returned value is a placeholder. 當您變更和部署合約時,變更的合約會部署於新的位址,且智慧型合約建構函式中會指派狀態變數的值。When you change and deploy the contract, the changed contract is deployed at a new address and the state variables are assigned values in the smart contract constructor. Truffle 範例 2_deploy_contracts.js 移轉指令碼會部署智慧型合約,並以引數的形式傳遞預留位置值。The Truffle sample 2_deploy_contracts.js migration script deploys the smart contract and passes a placeholder value as an argument. 建構函式會將 RequestMessage 狀態變數設定為預留位置值,系統所傳回的便是此值。The constructor sets the RequestMessage state variable to the placeholder value and that's what is returned.

  1. 若要設定 RequestMessage 狀態變數並查詢值,請再次執行 sendrequest.jsgetmessage.js 指令碼。To set the RequestMessage state variable and query the value, run the sendrequest.js and getmessage.js scripts again.

    Sendrequest 和 getmessage 腳本的輸出顯示已設定 RequestMessage

    sendrequest.js 會將 RequestMessage 狀態變數設定為 Hello, blockchain!sendrequest.js sets the RequestMessage state variable to Hello, blockchain! ,而且 getmessage.js 會查詢合約中是否有 RequestMessage 狀態變數的值,並傳回 Hello, blockchain!and getmessage.js queries the contract for value of RequestMessage state variable and returns Hello, blockchain!.

清除資源Clean up resources

您可以刪除不再需要的資源,方法是刪除您在 建立區塊鏈成員 必要條件快速入門中所建立的 myResourceGroup 資源群組。When no longer needed, you can delete the resources by deleting the myResourceGroup resource group you created in the Create a blockchain member prerequisite quickstart.

若要刪除資源群組:To delete the resource group:

  1. 在 Azure 入口網站中,瀏覽至左側瀏覽窗格中的 [資源群組],然後選取您想要刪除的資源群組。In the Azure portal, navigate to Resource group in the left navigation pane and select the resource group you want to delete.
  2. 選取 [刪除資源群組]。Select Delete resource group. 輸入資源群組名稱並選取 [刪除],以確定進行刪除。Verify deletion by entering the resource group name and select Delete.

後續步驟Next steps

在本教學課程中,您已使用 Azure 區塊鏈服務開發套件建立 Solidity 專案範例。In this tutorial, you created a sample Solidity project using Azure Blockchain Development Kit. 您已建置並部署智慧型合約,然後在裝載於 Azure 區塊鏈服務的區塊鏈聯盟網路上,透過交易呼叫了函式。You built and deployed a smart contract then called a function via a transaction on a blockchain consortium network hosted on Azure Blockchain Service.