LoginSignup
8
2

More than 5 years have passed since last update.

【Blockchain】Truffle.jsフレームワーク

Last updated at Posted at 2019-05-08

Ethereum には SmartContract の開発、テスト、デプロイをするためのフレームワーク Truffle.js をインストールして、利用してみたいと思います。

インストール

npm install truffle -g

プロジェクト作成

任意のプロジェクトフォルダを作成し、次のコマンドをターミナルで実行します。

truffle init

すると、プロジェクトの基本構造が作成されていることを確認できます。

任意のプロジェクトフォルダ/
├─ contracts
│  └─ Migrations.sol
├─ migrations
│  └─ 1_initial_migration.js
├─ test
└─ truffle-config.js

Compile

次のコマンドで contracts/ フォルダ内にある全ての SmartContract をコンパイルします。
コンパイル結果は、 build/ フォルダに出力されます。

truffle compile

Deploy

truffle-config.js にデプロイ先のネットワークを設定します。
この例では、ローカル環境(Ganache) を設定します。
development は、任意のネットワーク名です。

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*",
      gas: 5000000
    },
  }
}

そして、次のコマンドでデプロイします。

truffle migrate --network development

Console

Truffle.js には、コンソール機能があり、ネットワークに接続をすることができます。

truffle console --network development

また、コンソールには Web3.js のライブラリを使うことができるので、ネットワークにいろんなリクエストをすることができます。

  • アカウントリストを取得
web3.eth.getAccounts(function(err, dat) { accounts = dat });
  • 指定のアカウント残高を取得 (単位: Wei)
web3.eth.getBalance(accounts[0]);
  • 変換 Ether → Wei
web3.utils.toWei('1', 'ether');
  • 変換 Wei → Ether
web3.utils.fromWei('1000000000000000000', 'ether');
  • トランザクション (アカウント0 から アカウント115ether を移す)
web3.eth.sendTransaction({from: accounts[0], to: accounts[1], value: web3.utils.toWei('15', 'ether')});
  • トランザクションの詳細確認
web3.eth.getTransaction('{トランザクションハッシュ}');
or
web3.eth.getTransactionReceipt('{トランザクションハッシュ}');
  • デプロイした SmartContract を取得・利用
SampleContract.deployed().then( c => instance = c );

# そしてinstanceの機能を呼ぶには
instance.{関数}({引数,...});

# アカウントとGASを指定するには
instance.{関数}({引数,...}, {from: {アカウント}, gas: 150000});
8
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
2