Truffle 快速入门

快速入门

  • 安装Truffle环境

  npm install -g truffle
  • 安装测试网络

  npm -g install ethereumjs-testrpc
  • 创建Truffle项目

  truffle init

Truffle将会自动下载相关依赖,创建目录

truffle_init.png
  • contracts: 智能合约代码
  • migrations: 部署文件
  • test: 测试文件
  • 配置Truffle

打开truffle.js
module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    }
  }
};

  • port : testrpc 端口
  • 编写合约

  • 新建合约文件DogMarket.sol

在contracts目录下新建DogMarket.sol文件

pragma solidity ^0.4.17;  //指定solidity版本

contract DogMarket {      //创建合约
        
        //保存领养信息
        mapping(uint => address)  public adopters; //映射,相当于JavaMap

        function adoptDog(uint dogId) public returns(uint) {
                adopters[dogId] = msg.sender;
                return dogId;
        }

        function getAdoptUser(uint dogId) public returns(address) {
            return adopters[dogId];
        }
}
  • 编译solidity文件
truffle compile
  • 部署合约

在migrations目录下新建1_deploy_contracts.js

var DogMarket = artifacts.require("./DogMarket.sol");//引入上一步编写的solidity文件

module.exports = function(deployer) {
  deployer.deploy(DogMarket);
};

  • 运行命令

truffle migrate/truffle deploy

运行该命令将会把我们的合约部署到测试网络上。

  • 测试合约

  • 在test目录下新建DogMarketTest.sol

pragma solidity ^0.4.0;

import "truffle/DeployedAddresses.sol";   //引入地址
import "truffle/Assert.sol";              //引入断言
import "../contracts/DogMarket.sol";      // 被测试合约

contract DogMarketTest {
        DogMarket market = DogMarket(DeployedAddresses.DogMarket());

        function testAdopt() public {
            uint petId = uint(11);
            uint dogId = market.adoptDog(petId);
             Assert.equal(petId, dogId, "Owner of pet ID 11.");
        }
}
  • 运行测试
truffle test
   /media/jayden/E4B0C898B0C8729A/blockChain/truffle/pet-shop/contracts/DogMarket.sol:13:9: Warning: Function state mutability can be restricted to view
        function getAdoptUser(uint dogId) public returns(address) {
        ^ (Relevant source part starts here and spans across multiple lines).



  DogMarketTest
    ✓ testAdopt (165ms)


  1 passing (1s)

由结果看出,我们的程序正确的返回了输入的petId,得到的dogId都是11,断言正确

你可能感兴趣的:(Truffle 快速入门)