演習 - スマート コントラクトを記述する

完了

このユニットでは、前に作成した newSolidityProject に新しいスマート コントラクトを追加します。

出荷コントラクトを作成する

次に作成するスマート コントラクトでは、オンライン マーケットプレースから購入した商品の状態を追跡します。 コントラクトが作成されると、出荷状態が Pending に設定されます。 商品が出荷されると、出荷状態が Shipped に設定され、イベントが生成されます。 配達が完了すると、商品の出荷状態が Delivered に設定され、別のイベントが生成されます。

この演習を開始するには:

  1. 作成したプロジェクトの contracts ディレクトリで、フォルダーを右クリックし、Shipping.sol という新しいファイルを作成することにします。

  2. 以下のコントラクトの内容をコピーし、新しいファイルに貼り付けます。

    pragma solidity >=0.4.25 <0.9.0;
    
    contract Shipping {
        // Our predefined values for shipping listed as enums
        enum ShippingStatus { Pending, Shipped, Delivered }
    
        // Save enum ShippingStatus in variable status
        ShippingStatus private status;
    
        // Event to launch when package has arrived
        event LogNewAlert(string description);
    
        // This initializes our contract state (sets enum to Pending once the program starts)
        constructor() public {
            status = ShippingStatus.Pending;
        }
        // Function to change to Shipped
        function Shipped() public {
            status = ShippingStatus.Shipped;
            emit LogNewAlert("Your package has been shipped");
        }
    
        // Function to change to Delivered
        function Delivered() public {
            status = ShippingStatus.Delivered;
            emit LogNewAlert("Your package has arrived");
        }
    
        // Function to get the status of the shipping
        function getStatus(ShippingStatus _status) internal pure returns (string memory) {
         // Check the current status and return the correct name
         if (ShippingStatus.Pending == _status) return "Pending";
         if (ShippingStatus.Shipped == _status) return "Shipped";
         if (ShippingStatus.Delivered == _status) return "Delivered";
        }
    
       // Get status of your shipped item
        function Status() public view returns (string memory) {
             ShippingStatus _status = status;
             return getStatus(_status);
        }
    }
    
  3. コントラクトの内容を調べて、動作を確認します。 コントラクトを正常にビルドできることを確認します。

  4. [エクスプローラー] ペインで、コントラクト名を右クリックし、[Build Contracts](コントラクトをビルドする) を選択してスマート コントラクトをコンパイルします。

移行を追加する

次に、コントラクトを Ethereum ネットワークにデプロイできるように、移行ファイルを追加しましょう。

  1. [エクスプローラー] ペインで、migrations フォルダーの上にマウス ポインターを移動し、[新しいファイル] を選択します。 ファイルに 2_Shipping.js という名前を付けます。

  2. 次のコードをファイルに追加します。

    const Shipping = artifacts.require("Shipping");
    
    module.exports = function (deployer) {
      deployer.deploy(Shipping);
    };
    

配置

次に、先に進む前に、コントラクトを正常にデプロイできることを確認します。 コントラクト名を右クリックして、[Deploy Contracts](コントラクトをデプロイする) を選択します。 表示されたウィンドウで、[開発] を選択し、デプロイが完了するまで待ちます。

出力ウィンドウの情報を確認します。 2_Shipping.js のデプロイを探します。

Screenshot showing the output window for the shipping contract migration.