以太坊 Truffle 合约创建 编译 迁移

1. 初始化项目

创建项目目录 myproject,命令行中进入项目目录,执行初始化命令:

truffle init

初始化后的目录结构:

myproject
├── contracts
│   └── Migrations.sol
├── migrations
│   ├── 1_initial_migration.js
├── test
└── truffle.js
  • contracts 目录存放合约代码。
  • migrations 目录存放迁移部署脚本。
  • test 目录存放合约测试脚本
  • truffle.js 是配置文件

2. 创建合约

新建合约文件 contracts/Storage.sol,代码:

pragma solidity ^0.4.8;

contract Storage {
  uint256 storedData;

  function set(uint256 data) public {
    storedData = data;
  }

  function get() constant public returns (uint256) {
    return storedData;
  }
}

3. 编译

$ truffle compile
Compiling ./contracts/Storage.sol...
Writing artifacts to ./build/contracts

编译后的文件会写入 ./build/contracts 目录中。

truffle 默认只编译修改过的合约,以提升编译效率,如果想编译全部合约,需要使用 -all 选项:

$ truffle compile --all

4. 迁移脚本

新建 migrations/2_storage_migration.js,代码:

var Storage = artifacts.require("Storage");
module.exports = function(deployer) {
      deployer.deploy(Storage);
};

如果合约的构造函数需要参数,那么就在 deploy() 中添加参数,例如:

// 合约的构造函数
constructor(string initialMsg) public {
    message = initialMsg;
}

// 构造脚本
deployer.deploy(Storage, "test message");

如果不设置构造参数,执行迁移时就会报错:

...
contract constructor expected 1 arguments, received 0
...

5. 安装 Testrpc

Testrpc 是部署合约的测试环境,安装:

sudo cnpm install -g ethereumjs-testrpc

启动:

$ testrpc

EthereumJS TestRPC v6.0.3 (ganache-core: 2.0.2)

Available Accounts
==================
(0) 0x1b3d34e61dc5a55e4faee0146b7ae1e02245de5a
(1) 0xa84ce9acbb3cf39e2bf914d8508e932f29f4d195
......

Private Keys
==================
(0) 81c0f72c52551175587b41a99ee7370240eddbe7a9d3a7597abac1a129e99ab9
(1) 3fcde8c01590e1c78b36127ab65cf7f3182eb6ea408c078645fa71fc73f94851
......

HD Wallet
==================
Mnemonic:      document sniff code summer update join buzz pigeon tenant broom evil cigar
Base HD Path:  m/44'/60'/0'/0/{account_index}

Listening on localhost:8545

6. 迁移合约

truffle.js

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*" 
    }
  }
};

项目目录下执行:

$ truffle migrate

Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0x0d5cc78e879e99a5eb2d6a0173c7cd8ac45fac6bba996d75d094b2850a5a3ab2
  Migrations: 0x39ca5cf895f20b0551d38e7dd34738288b824996
Saving successful migration to network...
  ... 0xf2a4040d9dc1fa27ca8e3ff971897241820aea74a7cdc521c92e1b5aeceea790
Saving artifacts...
Running migration: 2_storage_migration.js
  Deploying Storage...
  ... 0xbad8750b6c8152f75cf20562d9ba3e7b0dfe8f59cb9e1e654e07a4f42f9758bd
  Storage: 0x861ca7c224612cf7928677a45dbfb60f2a0118cf
Saving successful migration to network...
  ... 0x51629e7370ebd2ec6e07df7b58a90d62ae0a3d6dc8d6a734f624a60a8890d43c
Saving artifacts...

这个命令会执行 migrations 中的迁移脚本,默认只执行新的,如果想重新执行全部迁移脚本,使用命令:

$ truffle migrate --reset

你可能感兴趣的:(以太坊 Truffle 合约创建 编译 迁移)