Truffle 실습

유지민·2022년 12월 13일
0

truffle

목록 보기
1/2

truffle 실습

Remix에서만 solidity를 진행 하다가 드디어 truffle을 시작하게 되었다.

Truffle이란?

Truffle은 스마트 컨트랙트 개발, 컴파일, 배포 그리고 테스팅을 쉽게 할 수 있도록 도와주는 프레임워크입니다.

실습 시작전 체크사항

  • Node.js
  • Truffle
  • vsCode
  • Ganache

Node.js는 설치가 되있어서 패스.

truffle부터 설치하자.

참고로 본인은 윈도우 환경이다.
PowerShell을 이용 해서 명령어 입력(관리자 권한으로 실행)

Truffle 설치

truffle 설치 명령어

npm install -g truffle

truffle 설치가 완료되면 명령어로 확인할 수 있다.

truffle version

여기서 설치는 잘되는데 트러플 버젼을 확인하려고 하면 계속 다음과 같은 오류가나서 엄청 해맸다.

truffle : 이 시스템에서 스크립트를 실행할 수 없으므로 C:\Users\Jimin\AppData\Roaming\npm\truffle.ps1 파일을 로드할 수
없습니다. 자세한 내용은 about_Execution_Policies(https://go.microsoft.com/fwlink/?LinkID=135170)를 참조하십시오.
위치 줄:1 문자:1
+ truffle
+ ~~~~~~~
    + CategoryInfo          : 보안 오류: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

천천히 오류를 읽어봐서 https://go.microsoft.com/fwlink/?LinkID=135170 요 사이트에서 읽어보면

PowerShell의 실행 정책은 PowerShell이 구성 파일을 로드하고 스크립트를 실행하는 조건을 제어하는 안전 기능입니다. 이 기능은 악성 스크립트의 실행을 방지하는 데 도움이 됩니다.

파워쉘의 실행 규칙 기본값은 Restricted라서 무슨 악성 스크립트가 실행될지 몰라서 차단한 것 이라고 한다.

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process

이 명령어로 Unrestricted 해주고 현재 켜져있는 파워쉥에서만 허용을 해주기 위해 -Scope Process 옵션을 추가 했다.
본인은 정작 이 오류를 못보고 어지간히 해매다 다른 분의 도움을 받았다.
오류를 차근차근 읽어보는 습관을 들이자.

위 명령어를 실행하고 다시 truffle버젼을 확인하면

Truffle v5.6.9 (core: 5.6.9)
Ganache v7.5.0
Solidity v0.5.16 (solc-js)
Node v16.17.1
Web3.js v1.7.4

이렇게 확인 가능하다.

Ganache 설치

https://trufflesuite.com/ganache/ 로 접속해 해당 운영체제 다운로드
설치 후 실행해 QUICKSTART.

실습

테스트 실습할 폴더를 하나 만들어 준다(그냥 마우스로 만들어도 된다)
후 만든 폴더로 이동

mkdir truffle_test

cd truffle_test

폴더 이동 후 truffle 프로젝트를 시작하는 명령어 입력

truffle init

하면 하위 폴더들이 생김 ls 명령어로 확인해주자

ls 


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2022-12-13  오후 10:40                build
d-----      2022-12-13  오후 10:47                contracts
d-----      2022-12-13  오후 10:48                migrations
d-----      2022-12-13  오후 10:30                test
-a----      2022-12-13  오후 10:40           5893 truffle-config.js

스마트 컨트랙트 생성

truffle create contract A

A라는 이름의 스마트 컨트랙트를 생성했다.
contracts폴더 이동 후 ls로 확인해보면

cd contracts
ls


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----      2022-12-13  오전 11:44              0 .gitkeep
-a----      2022-12-13  오후 10:39            159 A.sol

A.sol이 생긴걸 확인


이제 코드를 확인해보자.
(원래 vim을 써보려고 했는데 일단 vsCode로 작업하였다. 추후 vim관련 자료도 올리자)

vsCode 실행후 폴더를 열어 A.sol코드를 작성하자. 간단하게 사칙연산 하는 코드이다.

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0; 
contract A {
	uint abc=0;
	function add(uint a, uint b) public view returns(uint) {
			return a+b;
	}
    
	function sub(uint a, uint b) public view returns(uint) {
			return a-b;
	}    
    
    function changeABC(uint a) public returns(uint) {
    	abc = a;
        return abc;
    }
}

작성을 하였으면 Ganache와 환경을 맞춰주자.

Ganache를 보면 Network ID와 포트번호가 나오는데 확인 후
Truffle로 다시가서 truffle-config.js의 67번째 줄쯤 가보면

// development: {
    //  host: "127.0.0.1",     // Localhost (default: none)
    //  port: 8545,            // Standard Ethereum port (default: none)
    //  network_id: "*",       // Any network (default: none)
    // },

가 주석 처리 되어있다. 주석 해제 후 port와 network_id 입력.

js파일 추가

migrations 폴더 안에 1_A_sol.js라는 파일 추가 후

// 장소 : ~~ 폴더 안 ~~ 파일
const solidity 파일명 = artifacts.require("solidity 파일명");

module.exports = function (deployer) {
  deployer.deploy(solidity 파일명);
};

작성 후 저장

Compile

truffle compile

컴파일 실행

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

    Warning: Function state mutability can be restricted to pure
 --> project:/contracts/A.sol:5:4:
  |
5 |     function add(uint a, uint b) public view returns(uint) {
  |     ^ (Relevant source part starts here and spans across multiple lines).

> Artifacts written to C:\Users\Jimin\Desktop\truffle_test\build\contracts
> Compiled successfully using:
   - solc: 0.8.17+commit.8df45f5f.Emscripten.clang

Migrate

truffle migrate

migrate 실행

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

    Warning: Function state mutability can be restricted to pure
 --> project:/contracts/A.sol:5:4:
  |
5 |     function add(uint a, uint b) public view returns(uint) {
  |     ^ (Relevant source part starts here and spans across multiple lines).

> Artifacts written to C:\Users\Jimin\Desktop\truffle_test\build\contracts
> Compiled successfully using:
   - solc: 0.8.17+commit.8df45f5f.Emscripten.clang


Starting migrations...
======================
> Network name:    'development'
> Network id:      5777
> Block gas limit: 6721975 (0x6691b7)


1_A_sol.js
==========

   Deploying 'A'
   -------------
   > transaction hash:    0x006cdf7aadde1e654e5b241432eb394124cfe1b251d59bbdb4f1fcf83479dd1a
   > Blocks: 0            Seconds: 0                                                                                                                                           
   > contract address:    0x91275Fb0f13c9BAdC9714cA50Acb8D453301571D
   > block number:        1
   > block timestamp:     1670939084
   > account:             0x5d754F43A87898ADe05A158b0e4c19019d2166Ea
   > balance:             99.99706202
   > gas used:            146899 (0x23dd3)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00293798 ETH

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

Truffle console

에러 없이 완료되면

Truffle console

을 실행시켜 console창 실행
아래처럼 보인다

truffle(development)>

함수를 실행시키기 전 Ganache에 가서 Contracts를 가보면

컨트랙트가 생긴걸 볼수있다 (A만 생겨야 정상)
들어가보면 상태변수 abc가 0인 상태로 있다.

이제 함수를 실행 시킬 차례

deploy가 된 계약을 변수로 설정한다.

let aa = await aa.deployed()
// 아래와 같은 결과가 보이게 된다.
undefined

함수 실행

aa.add(1,2)	
aa.sub(2,1)
aa.changeABC(5);

위의 두개는 각각 3, 1의 결과가 리턴되고 3번째는5를 리턴하고
Ganache에가서 확인해보면 abc = 5가 되어있음을 확인할 수 있다.

profile
개발 취준생

0개의 댓글