Programming

블록체인 개발자를 위한 Truffle 사용법 - 스마트 계약(Smart Contract)개발

IT오이시이 2023. 7. 29. 00:16
728x90

블록체인 개발자를 위한 Truffle 사용법 - 스마트 계약(Smart Contract)개발

 
Truffle 설치 와 스마트 계약(Smart Contract) 개발

1. Truffle 설치 - 스마트 계약 개발 환경 구성 (truffle, ganache-cli, solc )
    - npm install -g truffle
    - npm install -g ganache-cli
    - npm install -g solc

2. Truffle 사용 - 스마트 계약(Smart Contract)개발
   - truffle create contract YourContractName
   - truffle create test YourTestName 

3. [Truffle 환경 설정] 컴파일 오류 대처 - Error: Failed to fetch the Solidity compiler from the following locations:
     - Are you connected to the internet?

4.  [Truffle 환경 설정] Deploy 오류 대처 - Error: Could not find artifacts for SimpleStorage from any sources
  - throw new Error("Could not find artifacts for " + import_path + " from any sources");

 

ㅁ Truffle 명령을 이용한 스마트 계약 개발


# Truffle을 이용하여 스마트 컨트렉트를 이용하는 명령은 다음과 같습니다.

$ ganache-cli  -h 0.0.0.0 -p 8545 &  # 테스트용 블록체인 네트웍을 작동 합니다.

$ truffle init
->  smart contract  소스를 작성 합니다.
$ truffle compile
$ truffle migration ./migration/deploy_someContract.js
$ truffle deploy
$ truffle test ./test/someContrace_test.js

이번에는 truffle init 부터 smart contract 을 개발하고 테스트 하는 과정을  알아 보고자 합니다.

 

2. Truffle - 스마트 계약(Smart Contract)개발

 

1. truffle 을 이용하여 프로젝트 생성 

Truffle 프로젝트 생성: 새로운 스마트 계약 프로젝트를 만들기 위해 프로젝트 디렉토리를 생성합니다. 그리고 해당 디렉토리로 이동한 후에 다음 명령을 실행하여 Truffle 프로젝트를 생성합니다. ( truffle init )
 

mkdir mySmartContract
cd mySmartContract

truffle init  # 현재 디렉토리를 초기화 합니다.

root@vm1 mySmartContract]# truffle init

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

> Copying project files to /app_svc/truffle2

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

 

truffle int을 실행하면 다음과 같은 디렉토리가 만들어 지며 해당 디렉토리에 개발을 하면 됩니다. 

- contracts/: Solidity 계약 소스 저장 디렉토리( Solidity contracts)
- migrations/: 배포용 스크립트 파일 디렉터리 (the scriptable deployment files)
- test/:      애플리케이션 및 계약을 테스트 스크립트 파일 ( test your application and contracts)
- truffle-config.js: The Truffle 기본 환경 설정 파일 (configuration file )

 

 

2. truffle 스마트 컨트렉트 작성

초기화된 폴더에서 샘플 스마트 계약과 테스트 스크립트를 작성합니다.

truffle create contract TestStorage
truffle create test TestStorage

# 다음과 같은 파일들이 작성이 되었습니다.
# ./contracts/local-dev/TestStorage.sol
# ./test/test_storage.js
#./truffle-config.js

 
 

3. truffle-config.js 수정

설치된 solc와 ganache-cli  설치 후에  "truffle-config.js"를 다음과 같이 수정합니다.
[주의사항]
아래 두개의 디렉토리가 설정이 되지 않았을 때 compile과 deploy에서 에러를 가질수 있습니다.
 contracts_build_directory: './build/local-contracts',  

 contracts_directory: './contracts/local-dev',
 

module.exports = {

  * contracts_build_directory tells Truffle where to store compiled contracts
  */
  contracts_build_directory: './build/local-contracts',

  /**
  * contracts_directory tells Truffle where the contracts you want to compile are located
  */
  contracts_directory: './contracts/local-dev',

  // $ truffle test --network <network-name>
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    }
  },
  // Configure your compilers
  compilers: {
    solc: {
      version: "0.8.4",       // 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 설치 :  https://couplewith.tistory.com/491
 
 

4. 스마트계약 : truffle compile  contract/contract-file.sol   > Artifacts 생성

- truffle compile contracts/local-dev/TestStorage.sol 를 실행하여 스마트 컨트렉트를 컴파일 합니다.
컴파일 명령이 실행 되면 Artifacts 파일을 생성합니다. "mySmartContract/build/local-contracts/SimpleStorage.json" 이 생성됩니다.

[ipman@vm1 mySmartContract]$ truffle compile contracts/SimpleStorage.sol

Compiling your contracts...
===========================
> Compiling ./contracts/SimpleStorage.sol
> Artifacts written to /app_svc/mySmartContract/build/local-contracts
> Compiled successfully using:
   - solc: 0.8.4+commit.c7e474f2.Emscripten.clang
   -----------------------------------------------
   
   
   # >> "mySmartContract/build/local-contracts/SimpleStorage.json" 이 생성됩니다.

 
[중요]
 컴파일 이후 Artifacts 파일이 만들어 지는 것이 중요합니다. 이파일이 있어야 "SimpleStorage"라는 인스턴스를 생성할 수 있게 됩니다.

[ipman@vm1 mySmartContract]$ cat build/local-contracts/SimpleStorage.json
{
  "contractName": "SimpleStorage",
  "abi": [
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "_data",
          "type": "uint256"
        }
      ],
      "name": "setData",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },

 

5. 스마트계약 - truffle  migrate

 
truffle migrate

[ipman@vm1 mySmartContract]$ truffle migrate

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.


Starting migrations...
======================
> Network name:    'development'
> Network id:      1690931129934
> Block gas limit: 30000000 (0x1c9c380)


1_deploy_contracts.js
=====================

   Deploying 'SimpleStorage'
   -------------------------
   > transaction hash:    0x912f8990e14ed891edb488d0dc9459098019793fe9b70fbf177f18ca17f819af
   > Blocks: 0            Seconds: 8
   > contract address:    0x7a41Ba959f4fC2a62eF2D180aF7d3FAde05D1939
   > block number:        11495
   > block timestamp:     1691046142
   > account:             0xFCF622435D8313F407fF99F46eAce78825Fa9456
   > balance:             999.999702897499168113
   > gas used:            118841 (0x1d039)
   > gas price:           2.500000007 gwei
   > value sent:          0 ETH
   > total cost:          0.000297102500831887 ETH

   > Saving artifacts
   -------------------------------------
   > Total cost:     0.000297102500831887 ETH

Summary
=======
> Total deployments:   1
> Final cost:          0.000297102500831887 ETH

 
 

6. 스마트계약 - truffle delploy 

 

[ipman@vm1 mySmartContract]$ truffle deploy

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.


Starting migrations...
======================
> Network name:    'development'
> Network id:      1690931129934
> Block gas limit: 30000000 (0x1c9c380)


1_deploy_contracts.js
=====================

   Deploying 'SimpleStorage'
   -------------------------
   > transaction hash:    0x7cf73156afca38d455beb6fed640441594301d7824fae4c90cf608ef1e4352a1
   > Blocks: 0            Seconds: 4
   > contract address:    0x3e9AB0F315d2488B86bB959a7CaF6Ad220D964d1
   > block number:        11634
   > block timestamp:     1691047543
   > account:             0xFCF622435D8313F407fF99F46eAce78825Fa9456
   > balance:             999.998702279996366384
   > gas used:            118841 (0x1d039)
   > gas price:           2.500000007 gwei
   > value sent:          0 ETH
   > total cost:          0.000297102500831887 ETH

   > Saving artifacts
   -------------------------------------
   > Total cost:     0.000297102500831887 ETH

Summary
=======
> Total deployments:   1
> Final cost:          0.000297102500831887 ETH

 
 

7. 스마트계약 테스트 - truffle test  [test-file.js]

truffle test 명령은 Truffle 프로젝트에서 작성한 스마트 계약에 대해 테스트를 실행하는 명령입니다. 이 명령은 스마트 계약에 대한 자동화된 테스트를 수행하여 계약의 동작을 확인하고 버그를 발견하는 데 도움을 줍니다.
truffle test 명령을 실행하면 Truffle은 자동화된 테스트를 시작합니다. Truffle은 test 디렉토리에 있는 스마트 계약 테스트 파일들을 찾아서 순차적으로 실행합니다.

# Truffle 테스트 사용법
---------------------------
# truffle test  [./path/to/test/file.js]
# truffle test


[ipman@vm1 mySmartContract]$ truffle test
Using network 'development'.


Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.


  Contract: SimpleStorage
    ? should set and get data correctly (9079ms)


  1 passing (9s)

 
Truffle은 테스트를 위해 자체적으로 가상 블록체인을 생성하고, 스마트 계약을 배포하여 실제 상황과 유사한 테스트 환경을 구축합니다. 이를 통해 개발자들은 스마트 계약의 동작을 신속하게 검증하고 테스트를 통해 안정성을 보장할 수 있습니다.

 

5. 스마트컨트렉트 예시( simpleStorage )

 
다음 두 파일을 생성하여 스마트계약을 테스트 합니다.
[contracts/SimpleStorage.sol]

// contracts/SimpleStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private data;

    function setData(uint256 _data) public {
        data = _data;
    }

    function getData() public view returns (uint256) {
        return data;
    }
}

 
[test/simpleStorage.test.js]

//test/simpleStorage.test.js
// 스마트 계약을 테스트하기 위해 필요한 객체들을 가져옵니다.
const SimpleStorage = artifacts.require("SimpleStorage");

// SimpleStorage 컨트랙트의 테스트 코드
contract("SimpleStorage", accounts => {
    // 계약이 정상적으로 배포되었는지 확인합니다.
    it("should deploy smart contract properly", async () => {
        const simpleStorage = await SimpleStorage.deployed();
        assert(simpleStorage.address !== "");
    });

    // 데이터를 저장하고 읽는 기능을 테스트합니다.
    it("should set and get data correctly", async () => {
        const simpleStorage = await SimpleStorage.deployed();

        // 데이터를 설정하고 저장합니다.
        const dataToSet = 42;
        await simpleStorage.setData(dataToSet);

        // 데이터를 읽어옵니다.
        const data = await simpleStorage.getData();

        // 데이터가 정확하게 저장되었는지 확인합니다.
        assert.equal(data, dataToSet, "Data was not set correctly.");
    });
});

 
[truffle-config.js]

module.exports = {  /**

  * contracts_build_directory tells Truffle where to store compiled contracts
  */
  contracts_build_directory: './build/local-contracts',

  /**
  * contracts_directory tells Truffle where the contracts you want to compile are located
  */
  contracts_directory: './contracts/local-dev',

  /**
   * 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: {
     development: {
       host: "127.0.0.1",     // Localhost (default: none)
       port: 8545,            // Standard Ethereum port (default: none)
       network_id: "*",       // Any network (default: none)
     }
   },

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

  // Configure your compilers
  compilers: {
    solc: {
      version: "0.8.4",       // 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 enabled in this project by default. Enabling Truffle DB surfaces access to the @truffle/db package
  // for querying data about the contracts, deployments, and networks in this project
  db: {
    enabled: true
  }
};

 

truffle test


 
 
https://dev.to/kevinmaarek/testing-your-smart-contract-with-truffle-3g6f

728x90
반응형