NFTをローカル環境で動かしてみるハンズオンです。
- Dockerを使うので、入ってない場合はインストールしてください。
TODO: ブロックチェーンの説明追加
TODO: スマートコントラクトの説明追加
名前 | 概要 |
---|---|
ganache | ローカルで開発用のprivateブロックチェーンを構築 |
truffle | スマートコントラクトの開発ツール(デプロイ、テストなど) |
まずは、開発環境を整えていきます。
- 本レポジトリをクローン
git clone [email protected]:tomokikun/nft-handson.git
- Dockerコンテナを起動
docker-compose up
- Imageをビルドした後、
truffle
コンテナとganache
コンテナが起動するはず。 - TODO: ganacheコンテナのログの内容の説明
- Imageをビルドした後、
- 別のターミナルを立ち上げる
- コンテナ内に入って作業する用です
truffle
コンテナに入るdocker exec -it nft-handson_truffle_1 sh
- (コンテナ名が異なる場合、
docker ps
で確認してください)
- truffleの確認
truffle -v
- truffleでテンプレートを生成
truffle init
- 以下のようなテンプレートが生成されるはず。
TODO: 生成されたファイルの説明truffle ├── contracts │ └── Migrations.sol ├── migrations │ └── 1_initial_migration.js ├── test └── truffle-config.js
truffle-config.js
のnetworks内のdevelopment
部分のコメントアウトを外し、host
を127.0.0.1
からganache
に変更...(略) networks: { ...(略) development: { host: "ganache", // Localhost (default: none) port: 8545, // Standard Ethereum port (default: none) network_id: "*", // Any network (default: none) }, ...(略) } ...(略)
ganache
とコンテナ名を指定すると、docker-compose
が自動的にIPアドレスに解決してくれます。
- ganacheの疎通確認
truffle console
truffle(development)>
と表示されたら成功- ganacheコンテナもログを出力しているはず
ctrl + d
でtruffleのコンソールから離脱
以上で準備完了です。
TODO: スマートコントラクトの説明
-
コントラクトを作成
truffle create contract HelloWorld
-
contracts/HelloWorld.sol
に以下と置き換える// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract HelloWorld { string greeting; constructor() { greeting = "Hello, Smart Contract!"; } function getMessage() public view returns (string memory) { return greeting; } }
-
コントラクトをデプロイするスクリプトを作成
truffle create migration HelloWorld
migrations/xxxxxxxxxx_hello_world.js
のようなファイルが生成させる
-
migrations/xxxxxxxxxx_hello_world.js
を以下のように書き換えるconst HelloWorld = artifacts.require("HelloWorld"); module.exports = function (_deployer) { // Use deployer to state migration tasks. _deployer.deploy(HelloWorld); };
-
デプロイ
truffle migrate
-
コントラクトのメソッドをコール
truffle console
- truffle console内で
const helloWorld = await HelloWorld.deployed()
- truffle console内で
helloWorld.getMessage()
- 以下のように表示されたら成功です!🎉
truffle(development)> helloWorld.getMessage() 'Hello, Smart Contract!'
- 以下のように表示されたら成功です!🎉
-
おまけ: ETHが減っていることを確認 ganacheを起動した時は100あったETHがデプロイによって少し減っていることが確認できます。
truffle(development)> const accounts = await web3.eth.getAccounts()
truffle(development)> const balance = await web3.eth.getBalance(accounts[0])
truffle(development)> await web3.utils.fromWei(balance)
'99.98961646'
準備中
準備中
より学びたい人のために、参考になる資料をまとめます。
TODO: 資料追加