练习 - 编写智能合同

已完成

在此单位中,我们将向前面创建的 newSolidityProject 添加新的智能合同。

创建装运合同

将创建的智能合同用于跟踪从在线市场购买的商品的状态。 创建该合同时,装运状态设置为 Pending。 装运商品后,则将装运状态设置为 Shipped 并会发出事件。 交货后,则将商品的装运状态设置为 Delivered,并发出另一个事件。

开始此练习:

  1. 在所创建项目的“合同”目录中,右键单击该文件夹,然后选择新建名为 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. 在“资源管理器”窗格中,右键单击该合同名称,然后选择“生成合同”以编译该智能合同。

添加迁移

现在我们将添加一个迁移文件,以便我们可以将该合同部署到 Ethereum 网络。

  1. 在“资源管理器”窗格中,将鼠标悬停在“迁移”文件夹上,然后选择“新建文件”。 将文件命名为 2_Shipping.js。

  2. 将以下代码添加到该文件:

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

部署

接下来要确保可以成功部署该合同,然后再继续。 右键单击合同名称,然后选择“部署合同”。 在显示的窗口中,选择“开发”,然后等待部署完成。

查看“输出”窗口中的信息。 查找 2_Shipping.js 的部署。

Screenshot showing the output window for the shipping contract migration.