[ganache/truffle/meta mask] ERC20 토큰 생성하고 메타마스크 지갑에 옮기기 - smart contract, 스마트 컨트랙트
본문 바로가기
Block Chain

[ganache/truffle/meta mask] ERC20 토큰 생성하고 메타마스크 지갑에 옮기기 - smart contract, 스마트 컨트랙트

by 쏠수있어ㅤ 2022. 3. 4.
반응형

스마트 컨트랙트 발생시켜서 ERC20규격의 토큰 생성하여 가나슈로 띄운 가상 블록 안에 트러플로 배포하기 

 

먼저 새 프로젝트를 열고, 

1. npm 시작하기 

npm init

 

2. truffle도 시작하기

truffle init 

 

3. contracts폴더 안 solidity 언어 스마트 컨트랙트 작성 

- OpenZeppelin 사이트에서 ERC20 + mintable 옵션이 추가된 소스코드 복사 

* 처음에 수량은 100,000,000으로 했다가 나중에 100,000으로 변경함 

 

 

 

4. 컴파일하기 

truffle compile

에러 발생

ParserError: Source "@openzeppelin/contracts/token/ERC20/ERC20.sol" not found

 

해결 방법  : openZeppelin 설치 

npm install @openzeppelin/contracts@3.x

다시 컴파일 해주니 이번엔 

버전 에러 발생 :  

pragma solidity >=0.6.0 <0.8.0;

 

해결 방법 : truffle-config.js - compilers 안 version을 컴파일할 .sol 파일의 pragma solidity 버전을 맞춰준다.

0.6.0으로 맞춰주었다. 

다시 컴파일을 하니 이번에는 아래와 같은 에러가 나왔다. 

Result of exponentiation has type uint8 and thus might overflow. Silence this warning by converting the literal to the expected type.

에러이제그만제발

 

해결법 : 코드에 10을 uint()로 감싸준다. 

    constructor() ERC20("practice", "PRT") {
        _mint(msg.sender, 100000 * uint(10) ** decimals());
    }

다시 컴파일을 해봤다. 

SyntaxError: No visibility specified. Did you intend to add "public"?
    constructor() ERC20("practice", "PRT") {

역시 에러다. 이번엔 public / private 타입을 적어달라고 하는 것 같다. 

 

해결법 : contructor() ERC20 끝에 public을 붙였다. 

contract Practice is ERC20, Ownable {
    constructor() ERC20("practice", "PRT") public {
        _mint(msg.sender, 100000 * uint(10) ** decimals());
    }

다시 truffle compile 명령어 실행.. 

성공이다 휴 

그럼 build라는 폴더가 생기고 안에 컴파일된 json파일들이 생긴다. 

 

 

 

 

5. 배포하기 

이제 배포만 하면되는데 배포할 블록체인 ganache 서버를 실행시켜줘야 한다. 

 

5-1) 아래 명령어로 ganache 실행 

ganache 

 

5-2) 메타마스크 크롬 확장프로그램에 다운받아 가입하기 

메타마스크 계정 추가 -> ganache를 실행했을 때 나오는 10개의 공개키-개인키 중 개인키 하나를 입력해주기 

그럼 ganache에서 테스트용으로 넣어둔 1,000ETH가 메타마스크에 보인다. 

 

5-3) truffle config에 network 설정

위의 상태로 배포를 해보면 연결이 안되어 있다고 나온다. truffle-config.js로 가서 network 부분을 수정해준다. (주석처리를 풀어주기만 하면 됨)

  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)
    },

127.0.0.1:8545 주소는 위의 메타마스크의 localhost8545를 뜻한다. 

 

5-4) migration을 해주는 스크립트 작성하기 

migrations 폴더에 .js 파일 만들어 아래 코드 작성 

require()안에 contracts폴더 안에 아까 만든 .sol 파일 넣어주기 

let practiceContract = artifacts.require("practiceContract.sol");

module.exports = function(deployer){
    deployer.deploy(practiceContract);
};

 

5-5) 배포하기

truffle migrate

에러가 났다

Error: Could not find artifacts for practiceContract from any sources

 

해결법 : 

contract이름 practice였는데  이걸 파일 (practiceContract)와 동일하게 맞춰주어야 한다. 아래처럼 수정

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract practiceContract is ERC20, Ownable {
    constructor() ERC20("practice", "PRT") public {
        _mint(msg.sender, 100000 * uint(10) ** decimals());
    }

    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}

 

다시 배포하면 아래처럼 ganache 블록체인 상에 배포가 되었다! 

ERC20 토큰 규격을 사용한 토큰을 이더리움 블록체인 안에 배포 완료!

account 는 아까 메타마스크에 개인키를 넣은 나의 테스트 계정이고

balance는 남은 ETH잔액,

gas price X gas used = 수수료가 나온다. 총 비용 0.00484967... ETH가 사용되었다. 

block timestamp 는 유닉스 시간 1970년1월1일부터 초로 환산한 시간을 도장으로 찍듯이 거래된 시각을 나타내준다.

 

 

 

6. 토큰 가져오깅

오픈재플린에서 ERC20을 사용해서 이름 "practice", 심볼 "PRT"라는 토큰 생성 코드를 만들어 사용했었다. 메타마스크의 토큰 가져오기로 해당 스마트 컨트랙트 주소를 넣고 가져온다.

 

다시 계좌로 돌아가보면 아래와 같이 이더리움과 내가 만든 토큰 PRT 100,000개를 볼 수 있다. PRT 토큰을 나의 다른 계정에 보낼 수 있다. Account 1로 50,000개의 PRT토큰을 보냈는데 처음에는 뜨지 않는다. 아까처럼 "토큰 가져오기"를 누르고 PRT 스마트 컨트랙트 주소를 눌러서 토큰을 가져와야 받은 토큰이 보인다.

 

 

 

ERC20 기반 토큰 생성 스마트컨트랙트 배포하기 끝!!

반응형

댓글