Truffle发布合约流程

初始化项目结构

1
2
3
mkdir demo
cd demo
truffle init

初始化工程目录后结构如下:

1
2
3
4
5
6
7
8
DaiZhiqing-Pro:demo daizhiqing$ tree
├── contracts
│ └── Migrations.sol
├── migrations
│ └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js
  • contract - Truffle默认的合约文件存放地址。
  • migrations - 存放发布脚本文件
  • test - 用来测试应用和合约的测试文件
  • truffle.js - Truffle的配置文件

修改配置文件

配置文件 truffle.js 里改成节点仿真器相关信息,节点仿真器使用的是 Canache
修改 truffle.js 配置文件:

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
networks: {
development:{
host:"127.0.0.1",
port:7545,
network_id:"*"
}
}
};

其中的host和port与节点仿真器设置中显示的配置保持一致。

编写合约

  • ./contracts/MyCoin.sol //合约文件

    1
    2
    3
    4
    5
    6
    7
    8
    pragma solidity ^0.4.17;
    contract MyCoin {

    //getBalance
    function getBalance() public pure returns(uint) {
    return 1;
    }
    }
  • ./migrations/2_deploy_contracts.js //合约发布文件

    1
    2
    3
    4
    5
    var MyCoin = artifacts.require("../contracts/MyCoin.sol");
    module.exports = function(deployer) {
    //add for demo
    deployer.deploy(MyCoin);
    };
  • ./test/testMyCoin.js //合约测试文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var MyCoinContract = artifacts.require("../contracts/MyCoin.sol");
    contract('BorrowContract', function(accounts) {
    var myCoinContract;
    //合约部署
    before(async () => {
    myCoinContract = await MyCoinContract.deployed();
    });
    it("return should equal 1", function() {
    return myCoinContract.getBalance.call().then(function(balance) {
    assert.equal(balance.valueOf(), 1, "return value is not 1");
    });
    });
    });

执行测试命令

1
truffle test

编译、部署合约

1
2
truffle compile  #编译合约
truffle migrate #部署合约

另一个方案

1
2
3
4
5
6
mkdir demo2
cd demo2
truffle unbox webpack
truffle compile
truffle deploy
npm run dev