본문 바로가기

블록체인/이더리움

[SpeedRunEthereum] Challenge 2 [Token Vendor]

Checkpoint 1: Environment

터미널 3개를 실행 후 하나씩 실행합니다.

yarn chain //로컬 네트워크
yarn start //리액트
yarn deploy //스마트 컨트랙트 배포

 

Checkpoint 2: Your Token

YourToken.sol의 생성자로 초기 물량을 발행합니다.

contract YourToken is ERC20 {
    constructor() ERC20("EBTT", "EBT") {
        _mint(msg.sender , 1000 * 10 ** 18);
    }
}

 

Checkpoint 3: Vendor

 

Vendor.sol 에서 다음 코드를 추가합니다. 

 uint256 public constant tokensPerEth = 100; // 이더당 토큰 개수
 event BuytTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens);
 
 // ToDo: create a payable buyTokens() function:
  function buyTokens() payable public {
    uint256 tokensBuying = msg.value * tokensPerEth;
    yourToken.transfer(msg.sender, tokensBuying);

    emit BuytTokens(msg.sender, msg.value, tokensBuying); 


  }

 

코드를 작성한 후 deploy 스크립트를 수정해줍니다. 01_deploy_vendor.js의 23~32라인의 주석을 풀어줍니다.

 

다시 재배포를 한 후 정상적으로 토큰 구매가 가능한 것을 확인한 후에 Vendor.sol에서 withdraw 함수를 작성합니다.

 function withdraw() payable public onlyOwner {
    require(address(this).balance > 0);
    msg.sender.call{value: address(this).balance}("");
  }

onlyOwner가 붙어있지만 현재 Vendor컨트랙트의 오너가 자신의 지갑이 아니므로 deploy 스크립트에서 transferownership으로 소유권을 이전합니다.

 

01_deploy_vendor.js에서 35~38라인의 주석을 풀어준 후 transferownership의 target address를 자신의 지갑 주소로 지정합니다.

 

Checkpoint 4: Vendor Buyback

 

Vendor에게 가지고 있는 토큰을 판매하는 sellTokens를 구현합니다.

function sellTokens(uint256 _amount) public {
    uint256 backEth = _amount / tokensPerEth;
    
    require(yourToken.balanceOf(msg.sender) * 10 ** 18 >= _amount, "your balance is lower than you requrested.");
    require(address(this).balance  > backEth, "Vendor doesn't have enough eth");

    uint256 amount = yourToken.allowance(msg.sender, address(this));
    require(amount >= _amount);
    bool res = yourToken.transferFrom(msg.sender, address(this), _amount);
    require(res, "transaction faild");
    (bool sent,) = msg.sender.call{value: backEth}("");
    require(res, "transaction faild");

    emit SellTokens(msg.sender, backEth, _amount);
      
  }

sellTokens를 호출하기 전에 먼저 Vendor는 토큰 홀더로부터 먼저 approve를 받은 후에 호출되어야만 합니다.

 

Checkpoint 5,6,7

컨트랙트 배포, 빌드, 검증까지 해주시면 완료입니다.

yarn deploy --network rinkeby
yarn build
yarn surge
yarn verify --network rinkeby