Skip to content

Instantly share code, notes, and snippets.

@Georgi87
Created April 30, 2017 11:01
Show Gist options
  • Save Georgi87/f992e7d3281162711dfd5471bddbc33e to your computer and use it in GitHub Desktop.
Save Georgi87/f992e7d3281162711dfd5471bddbc33e to your computer and use it in GitHub Desktop.
pragma solidity 0.4.10;
contract Token {
function transfer(address to, uint256 value) returns (bool success);
function balanceOf(address owner) constant returns (uint256 balance);
}
contract IOU {
address public owner;
Token public token;
uint public price;
uint public totalSold;
mapping (address => uint) public balances;
Stages public stage;
enum Stages {
BuyTokens,
TransferTokens
}
modifier isOwner() {
if (msg.sender != owner)
throw;
_;
}
modifier atStage(Stages _stage) {
if (stage != _stage)
throw;
_;
}
function IOU(address _token, uint _price)
public
{
if (_token == 0 || _price == 0)
throw;
token = Token(_token);
price = _price;
owner = msg.sender;
stage = Stages.BuyTokens;
}
function lowerPrice(uint _price)
public
isOwner
{
if (_price > price)
throw;
price = _price;
}
function sendTransaction(address destination, bytes data)
public
payable
isOwner
{
if (destination == address(token))
// Owner cannot interact with token contract
throw;
if (!destination.call.value(msg.value)(data))
throw;
}
function buyIOU()
public
payable
atStage(Stages.BuyTokens)
returns (uint amount)
{
uint tokensToSell = token.balanceOf(this) - totalSold;
amount = msg.value / price;
if (amount > tokensToSell)
amount = tokensToSell;
uint refund = msg.value - amount * price;
if (refund > 0 && !msg.sender.send(refund))
throw;
if (!owner.send(msg.value - refund))
throw;
totalSold += amount;
balances[msg.sender] += amount;
}
function startTransfers()
public
atStage(Stages.BuyTokens)
returns (uint amount)
{
amount = token.balanceOf(this) - totalSold;
if (amount > 0 && !token.transfer(owner, amount))
throw;
stage = Stages.TransferTokens;
}
function transferIOU(address to)
public
atStage(Stages.TransferTokens)
returns (uint amount)
{
amount = balances[msg.sender];
balances[msg.sender] = 0;
if (!token.transfer(to, amount))
throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment