본문 바로가기
IT/이더리움 Ethereum

이더리움 DApp 개발을 위한 Truffle(트러플) 설치하기 . solidity 컴파일

by SidePower 2022. 9. 23.

Truffle는 이더리움 스마트 계약(Smart Contract)을 만드는 개발 언어인

solidity를 컴파일하고 스마트 계약을 테스트를 할 수 있으며

배포까지 할수 있는 개발 환경입니다.

 

http://trufflesuite.com/

TRUFFLE에 대해 아래와 같이 설명되어 있네요.

개발자로서의 삶을 더 쉽게 만드는 것을 목표로 하는 

이더리움 가상 머신(EVM)을 사용하는 블록체인을 위한 

세계적 수준의 개발 환경, 테스트 프레임워크 및 자산 파이프라인.

 

 

트러플은 node.js 플랫폼에서 npm 명령어로 설치할 수 있습니다.

트러플 홈페이지에 설치 명령어가 있네요.

ngm install truffle -g

 

 

npm은 node.js를 설치하면 자동으로 설치되는 패키지 관리 툴입니다.

 truffle 폴더 만들기
폴더 안 만드셔도 됩니다. ㅋ
PS C:\> mkdir truffle


    디렉터리: C:\

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2021-12-20  오후 10:52                truffle

PS C:\> dir

    디렉터리: C:\

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2021-12-19  오후 11:22                nodejs
d-----      2019-12-07   오후 6:14                PerfLogs
d-r---      2021-12-19  오후 11:01                Program Files
d-r---      2021-12-19  오후 11:01                Program Files (x86)
d-----      2021-12-19  오후 10:43                Python310
d-----      2021-12-20  오후 10:52                truffle
d-r---      2021-12-19   오후 2:11                Users
d-----      2021-12-19  오후 10:42                Windows

PS C:\> cd truffle

PS C:\truffle> npm install truffle -g
[#####.............] | idealTree:camel-case: sill fetch manifest tslib@^1.10.0
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated redux-devtools-instrument@1.10.0: Package moved to @redux-devtools/instrument.
npm WARN deprecated ipld-raw@6.0.0: This module has been superseded by the multiformats module
npm WARN deprecated remotedev-serialize@0.1.9: Package moved to @redux-devtools/serialize.
npm WARN deprecated multicodec@1.0.4: This module has been superseded by the multiformats module
npm WARN deprecated multibase@0.7.0: This module has been superseded by the multiformats module
npm WARN deprecated multibase@0.6.1: This module has been superseded by the multiformats module
npm WARN deprecated apollo-tracing@0.15.0: The `apollo-tracing` package is no longer part of Apollo Server 3. See https://www.apollographql.com/doc

설치 진행중....
시간이 좀 걸리네요. ^^;; 5분정도..

Run `npm audit` for details.
npm notice
npm notice New minor version of npm available! 8.1.2 -> 8.3.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.3.0
npm notice Run npm install -g npm@8.3.0 to update!
npm notice
마지막 출력내용이 여기까지 보이면 설치 완료된거에요.


 truffle 버전확인
C:\Users\bedro>truffle version
Truffle v5.4.25 (core: 5.4.25)
Solidity v0.5.16 (solc-js)
Node v16.13.1
Web3.js v1.5.3

truffle , solidity , node . web3까지 동시에 버전 확인이 되네요.

 

● 트러플 개발 환경 만들기

 Truffle 프로젝트 생성

프로젝트로 사용할 폴더를 하나 만드세요.
project dapp를 줄여서 pjdapp로 정합니다.

C:\>mkdir pjdapp
C:\>cd pjdapp
C:\pjdapp>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp 디렉터리

2021-12-20  오후 10:52    <DIR>          .
2021-12-20  오후 10:52    <DIR>          ..
               0개 파일                   0 바이트
               2개 디렉터리  71,279,087,616 바이트 남음


 truffle init 명령어로 프로젝트 환경 만들기

C:\pjdapp>truffle init

Starting init...
================

> Copying project files to C:\pjdapp

Init successful, sweet!

Try our scaffold commands to get started:
  $ truffle create contract YourContractName # scaffold a contract
  $ truffle create test YourTestName         # scaffold a test

http://trufflesuite.com/docs


C:\pjdapp>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp 디렉터리

2021-12-20  오후 11:26    <DIR>          .
2021-12-20  오후 11:26    <DIR>          ..
2021-12-20  오후 11:26    <DIR>          contracts
2021-12-20  오후 11:26    <DIR>          migrations
2021-12-20  오후 11:26    <DIR>          test
2021-12-20  오후 10:59             4,901 truffle-config.js
               1개 파일               4,901 바이트
               5개 디렉터리  71,297,568,768 바이트 남음

contracts : 스마트 계약 소스
migrations : 스마트 계약 배포
test : 테스트 소스
truffle-config.js : 네트워크 설정과 solidity 컴파일 버전 등

이렇게 트러플 프로젝트 디렉터리와 파일들이 자동으로 생성되었습니다.

 

 truffle-config.js 파일 내용

networks와 compilers 두 부분으로 나눠져 있네요.

networks는 이더리움 네트워크 연결 설정이며 다음에 실제로 연결할 때 다룰 거예요.

compilers는 solidity 컴파일러인 solc 설정입니다. 

solc 버전 정보를 알고만 있으면 될 거 같네요.

/**
 * Use this file to configure your truffle project. It's seeded with some
 * common settings for different networks and features like migrations,
 * compilation and testing. Uncomment the ones you need or modify
 * them to suit your project as necessary.
 *
 * More information about configuration can be found at:
 *
 * trufflesuite.com/docs/advanced/configuration
 *
 * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
 * to sign your transactions before they're sent to a remote public node. Infura accounts
 * are available for free at: infura.io/register.
 *
 * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
 * public/private key pairs. If you're publishing your code to GitHub make sure you load this
 * phrase from a file you've .gitignored so it doesn't accidentally become public.
 *
 */

// const HDWalletProvider = require('@truffle/hdwallet-provider');
//
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();

module.exports = {
  /**
   * Networks define how you connect to your ethereum client and let you set the
   * defaults web3 uses to send transactions. If you don't specify one truffle
   * will spin up a development blockchain for you on port 9545 when you
   * run `develop` or `test`. You can ask a truffle command to use a specific
   * network from the command line, e.g
   *
   * $ truffle test --network <network-name>
   */

  networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
    // development: {
    //  host: "127.0.0.1",     // Localhost (default: none)
    //  port: 8545,            // Standard Ethereum port (default: none)
    //  network_id: "*",       // Any network (default: none)
    // },
    // Another network with more advanced options...
    // advanced: {
    // port: 8777,             // Custom port
    // network_id: 1342,       // Custom network
    // gas: 8500000,           // Gas sent with each transaction (default: ~6700000)
    // gasPrice: 20000000000,  // 20 gwei (in wei) (default: 100 gwei)
    // from: <address>,        // Account to send txs from (default: accounts[0])
    // websocket: true        // Enable EventEmitter interface for web3 (default: false)
    // },
    // Useful for deploying to a public network.
    // NB: It's important to wrap the provider as a function.
    // ropsten: {
    // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
    // network_id: 3,       // Ropsten's id
    // gas: 5500000,        // Ropsten has a lower block limit than mainnet
    // confirmations: 2,    // # of confs to wait between deployments. (default: 0)
    // timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
    // skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )
    // },
    // Useful for private networks
    // private: {
    // provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
    // network_id: 2111,   // This network is yours, in the cloud.
    // production: true    // Treats this network as if it was a public net. (default: false)
    // }
  },

  // Set default mocha options here, use special reporters etc.
  mocha: {
    // timeout: 100000
  },

  // Configure your compilers
  compilers: {
    solc: {
      version: "0.8.10",    // Fetch exact version from solc-bin (default: truffle's version)
      // docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
      // settings: {          // See the solidity docs for advice about optimization and evmVersion
      //  optimizer: {
      //    enabled: false,
      //    runs: 200
      //  },
      //  evmVersion: "byzantium"
      // }
    }
  },

  // Truffle DB is currently disabled by default; to enable it, change enabled:
  // false to enabled: true. The default storage location can also be
  // overridden by specifying the adapter settings, as shown in the commented code below.
  //
  // NOTE: It is not possible to migrate your contracts to truffle DB and you should
  // make a backup of your artifacts to a safe location before enabling this feature.
  //
  // After you backed up your artifacts you can utilize db by running migrate as follows: 
  // $ truffle migrate --reset --compile-all
  //
  // db: {
    // enabled: false,
    // host: "127.0.0.1",
    // adapter: {
    //   name: "sqlite",
    //   settings: {
    //     directory: ".db"
    //   }
    // }
  // }
};

 

 truffle 샘플 프로젝트 개발하기

간단한 개발 절차입니다.

스마트 계약 소스 작성 + 컴파일(빌드) + 이더리움 블록체인 배포하기 + 테스트해보기

 스마트 계약 소스 작성
간단하게 문자열을 주고 받는 소스를 만들겠습니다.

C:\pjdapp>cd contracts

C:\pjdapp\contracts>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp\contracts 디렉터리

2021-12-20  오후 11:48    <DIR>          .
2021-12-20  오후 11:48    <DIR>          ..
2021-12-20  오후 11:49               286 Hello.sol
2021-12-20  오후 10:59               419 Migrations.sol
               2개 파일                 705 바이트
               2개 디렉터리  71,292,645,376 바이트 남음


 Hello.sol
pragma solidity ^0.8.10;

contract Hello {
    string public greet;

    constructor(string memeoy _greet) {
        greet = _greet;
    }

    function setGreet(string memory _greet) public {
        greet = _greet;
    }

    function getGreet() public view returns(string){
        return greet;
    }
}


 solidity 컴파일
C:\pjdapp\contracts>truffle compile

Compiling your contracts...
===========================
> Compiling .\contracts\Hello.sol
> Compiling .\contracts\Migrations.sol
> Compilation warnings encountered:

    Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.
--> project:/contracts/Hello.sol
SPDX license 경고는 소스안에 저작권 표시되지 않아 발생합니다.
소스 맨 위에 아래 한줄 넣어주면 사라집니다. 

// SPDX-License-Identifier: UNLICENSED

> Artifacts written to C:\pjdapp\build\contracts
> Compiled successfully using:
   - solc: 0.8.10+commit.fc410830.Emscripten.clang


 컴파일이 정상이면 build 폴더가 새로 생성되고
build 폴더안에 sol파일들이 json파일로 만들어집니다.

C:\pjdapp\contracts>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp\contracts 디렉터리

2021-12-20  오후 11:48    <DIR>          .
2021-12-20  오후 11:48    <DIR>          ..
2021-12-21  오전 12:09               293 Hello.sol
2021-12-20  오후 10:59               419 Migrations.sol
               2개 파일                 712 바이트
               2개 디렉터리  71,263,485,952 바이트 남음

C:\pjdapp\contracts>cd ../

C:\pjdapp>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp 디렉터리

2021-12-21  오전 12:09    <DIR>          .
2021-12-21  오전 12:09    <DIR>          ..
2021-12-21  오전 12:09    <DIR>          build
2021-12-20  오후 11:48    <DIR>          contracts
2021-12-20  오후 11:26    <DIR>          migrations
2021-12-20  오후 11:26    <DIR>          test
2021-12-20  오후 10:59             4,901 truffle-config.js
               1개 파일               4,901 바이트
               6개 디렉터리  71,263,358,976 바이트 남음

C:\pjdapp>cd build

C:\pjdapp\build>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp\build 디렉터리

2021-12-21  오전 12:09    <DIR>          .
2021-12-21  오전 12:09    <DIR>          ..
2021-12-21  오전 12:09    <DIR>          contracts
               0개 파일                   0 바이트
               3개 디렉터리  71,263,031,296 바이트 남음

C:\pjdapp\build>cd contracts

C:\pjdapp\build\contracts>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\pjdapp\build\contracts 디렉터리

2021-12-21  오전 12:09    <DIR>          .
2021-12-21  오전 12:09    <DIR>          ..
2021-12-21  오전 12:09           216,312 Hello.json
2021-12-21  오전 12:09            90,332 Migrations.json
               2개 파일             306,644 바이트
               2개 디렉터리  71,262,871,552 바이트 남음

컴파일까지 정상인 거 확인되었네요.

다음에 이더리움 테스트넷에 배포해서 테스트까지 해볼 거예요.

반응형

댓글