Transaction Hash:
Block:
5435218 at Apr-13-2018 09:04:47 PM +UTC
Transaction Fee:
0.00199401 ETH
$3.90
Gas Used:
398,802 Gas / 5 Gwei
Emitted Events:
| 88 |
DSToken.Transfer( src=[Sender] 0x1114fa65a2f3d01b045dc2c22cfb224af4f16198, dst=BancorQuickConverter, wad=413715882141787487297 )
|
| 89 |
DSToken.Approval( src=BancorQuickConverter, guy=[Receiver] BancorConverter, wad=413715882141787487297 )
|
| 90 |
DSToken.Transfer( src=BancorQuickConverter, dst=[Receiver] BancorConverter, wad=413715882141787487297 )
|
| 91 |
SmartToken.Issuance( _amount=91549526028592620280 )
|
| 92 |
SmartToken.Transfer( _from=SmartToken, _to=BancorQuickConverter, _value=91549526028592620280 )
|
| 93 |
BancorConverter.Conversion( _fromToken=DSToken, _toToken=SmartToken, _trader=BancorQuickConverter, _amount=413715882141787487297, _return=91549526028592620280, _currentPriceN=207244384418058340855382000000, _currentPriceD=45883216136688672234096000000 )
|
| 94 |
SmartToken.Transfer( _from=BancorQuickConverter, _to=SmartToken, _value=91549526028592620280 )
|
| 95 |
SmartToken.Destruction( _amount=91549526028592620280 )
|
| 96 |
SmartToken.Transfer( _from=[Receiver] BancorConverter, _to=BancorQuickConverter, _value=140047009416894951031 )
|
| 97 |
BancorConverter.Conversion( _fromToken=SmartToken, _toToken=SmartToken, _trader=BancorQuickConverter, _amount=91549526028592620280, _return=140047009416894951031, _currentPriceN=45837441373674375923956000000, _currentPriceD=70154686782227146112330000000 )
|
| 98 |
SmartToken.Transfer( _from=BancorQuickConverter, _to=SmartToken, _value=140047009416894951031 )
|
| 99 |
SmartToken.Destruction( _amount=140047009416894951031 )
|
| 100 |
EtherToken.Transfer( _from=BancorConverter, _to=BancorQuickConverter, _value=844791992605807571 )
|
| 101 |
BancorConverter.Conversion( _fromToken=SmartToken, _toToken=EtherToken, _trader=BancorQuickConverter, _amount=140047009416894951031, _return=844791992605807571, _conversionFee=0, _currentPriceN=7498140147000067203546801500000, _currentPriceD=45229923455070024199537000000 )
|
| 102 |
EtherToken.Transfer( _from=BancorQuickConverter, _to=EtherToken, _value=844791992605807571 )
|
| 103 |
EtherToken.Destruction( _amount=844791992605807571 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x1114fa65...af4f16198 |
0.071325151104581046 Eth
Nonce: 318
|
0.914123133710388617 Eth
Nonce: 319
| 0.842797982605807571 | ||
| 0x1F573D6F...d79a7FF1C | |||||
|
0x2a65Aca4...135398226
Miner
| (DwarfPool) | 545.868178898209639659 Eth | 545.870172908209639659 Eth | 0.00199401 | |
| 0x80353044...D98a42C59 | |||||
| 0x89d24A6b...a23260359 | |||||
| 0xc0829421...2db2cE315 | 18,972.089061989721194303 Eth | 18,971.244269997115386732 Eth | 0.844791992605807571 |
Execution Trace
BancorConverter.quickConvert( _path=[0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359, 0xee01b3AB5F6728adc137Be101d99c678938E6E72, 0xee01b3AB5F6728adc137Be101d99c678938E6E72, 0xee01b3AB5F6728adc137Be101d99c678938E6E72, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315], _amount=413715882141787487297, _minReturn=839187833702203000 ) => ( 844791992605807571 )
-
BancorConverterExtensions.CALL( ) -
DSToken.transferFrom( src=0x1114fa65a2f3D01B045DC2c22cFB224af4f16198, dst=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, wad=413715882141787487297 ) => ( True )
BancorQuickConverter.convertFor( _path=[0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359, 0xee01b3AB5F6728adc137Be101d99c678938E6E72, 0xee01b3AB5F6728adc137Be101d99c678938E6E72, 0xee01b3AB5F6728adc137Be101d99c678938E6E72, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315], _amount=413715882141787487297, _minReturn=839187833702203000, _for=0x1114fa65a2f3D01B045DC2c22cFB224af4f16198 ) => ( 844791992605807571 )
-
SmartToken.CALL( )
-
DSToken.allowance( src=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, guy=0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 0 )
-
DSToken.allowance( src=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, guy=0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 0 )
-
DSToken.approve( guy=0x578f3c8454F316293DBd31D8C7806050F3B3E2D8, wad=413715882141787487297 ) => ( True )
BancorConverter.change( _fromToken=0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359, _toToken=0xee01b3AB5F6728adc137Be101d99c678938E6E72, _amount=413715882141787487297, _minReturn=1 ) => ( 91549526028592620280 )-
BancorConverterExtensions.CALL( ) -
BancorGasPriceLimit.CALL( ) -
SmartToken.CALL( )
-
SmartToken.CALL( )
-
DSToken.balanceOf( src=0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 206830668535916553368085 )
-
BancorConverterExtensions.CALL( ) -
BancorFormula.calculatePurchaseReturn( _supply=91674882747348751847912, _reserveBalance=206830668535916553368085, _reserveRatio=500000, _depositAmount=413715882141787487297 ) => ( 91641167195788408688 ) -
DSToken.transferFrom( src=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, dst=0x578f3c8454F316293DBd31D8C7806050F3B3E2D8, wad=413715882141787487297 ) => ( True )
-
SmartToken.issue( _to=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, _amount=91549526028592620280 )
-
DSToken.balanceOf( src=0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 207244384418058340855382 )
-
SmartToken.CALL( )
-
SmartToken.CALL( )
-
DSToken.CALL( )
-
-
SmartToken.CALL( )
BancorConverter.change( _fromToken=0xee01b3AB5F6728adc137Be101d99c678938E6E72, _toToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _amount=91549526028592620280, _minReturn=1 ) => ( 140047009416894951031 )-
BancorConverterExtensions.CALL( ) -
BancorGasPriceLimit.CALL( ) -
SmartToken.balanceOf( 0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1 ) => ( 91549526028592620280 )
-
SmartToken.CALL( )
-
SmartToken.CALL( )
-
SmartToken.balanceOf( 0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 70294733791644041063361 )
-
BancorConverterExtensions.CALL( ) -
BancorFormula.calculateSaleReturn( _supply=91766432273377344468192, _reserveBalance=70294733791644041063361, _reserveRatio=500000, _sellAmount=91549526028592620280 ) => ( 140187196613508459490 ) -
SmartToken.CALL( )
-
SmartToken.balanceOf( 0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 70294733791644041063361 )
-
SmartToken.destroy( _from=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, _amount=91549526028592620280 )
-
SmartToken.transfer( _to=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, _value=140047009416894951031 ) => ( success=True )
-
SmartToken.balanceOf( 0x578f3c8454F316293DBd31D8C7806050F3B3E2D8 ) => ( 70154686782227146112330 )
-
SmartToken.CALL( )
-
SmartToken.CALL( )
-
SmartToken.CALL( )
-
-
SmartToken.CALL( )
BancorConverter.change( _fromToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _toToken=0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315, _amount=140047009416894951031, _minReturn=839187833702203000 ) => ( 844791992605807571 )-
BancorConverterExtensions.CALL( ) -
BancorGasPriceLimit.CALL( ) -
SmartToken.balanceOf( 0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1 ) => ( 140047009416894951031 )
-
SmartToken.CALL( )
-
SmartToken.CALL( )
-
BancorConverterExtensions.CALL( ) -
BancorFormula.calculateSaleReturn( _supply=74981541517010088930419046, _reserveBalance=45230768247062630007108, _reserveRatio=100000, _sellAmount=140047009416894951031 ) => ( 844791992605807571 ) -
SmartToken.CALL( )
-
SmartToken.destroy( _from=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, _amount=140047009416894951031 )
-
EtherToken.transfer( _to=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, _value=844791992605807571 ) => ( success=True )
-
SmartToken.CALL( )
-
SmartToken.CALL( )
-
EtherToken.CALL( )
-
EtherToken.withdrawTo( _to=0x1114fa65a2f3D01B045DC2c22cFB224af4f16198, _amount=844791992605807571 )
- ETH 0.844791992605807571
0x1114fa65a2f3d01b045dc2c22cfb224af4f16198.CALL( )
- ETH 0.844791992605807571
-
quickConvert[BancorConverter (ln:852)]
quickConverter[BancorConverter (ln:859)]destroy[BancorConverter (ln:867)]issue[BancorConverter (ln:868)]transferFrom[BancorConverter (ln:872)]value[BancorConverter (ln:877)]
File 1 of 10: BancorConverter
File 2 of 10: BancorQuickConverter
File 3 of 10: DSToken
File 4 of 10: SmartToken
File 5 of 10: SmartToken
File 6 of 10: BancorConverter
File 7 of 10: EtherToken
File 8 of 10: BancorConverterExtensions
File 9 of 10: BancorGasPriceLimit
File 10 of 10: BancorFormula
pragma solidity ^0.4.11;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal constant returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal constant returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal constant returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) {}
function symbol() public constant returns (string) {}
function decimals() public constant returns (uint8) {}
function totalSupply() public constant returns (uint256) {}
function balanceOf(address _owner) public constant returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
Provides support and utilities for contract management
*/
contract Managed {
address public manager;
address public newManager;
event ManagerUpdate(address _prevManager, address _newManager);
/**
@dev constructor
*/
function Managed() {
manager = msg.sender;
}
// allows execution by the manager only
modifier managerOnly {
assert(msg.sender == manager);
_;
}
/**
@dev allows transferring the contract management
the new manager still needs to accept the transfer
can only be called by the contract manager
@param _newManager new contract manager
*/
function transferManagement(address _newManager) public managerOnly {
require(_newManager != manager);
newManager = _newManager;
}
/**
@dev used by a new manager to accept a management transfer
*/
function acceptManagement() public {
require(msg.sender == newManager);
ManagerUpdate(manager, newManager);
manager = newManager;
newManager = 0x0;
}
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
EIP228 Token Converter interface
*/
contract ITokenConverter {
function convertibleTokenCount() public constant returns (uint16);
function convertibleToken(uint16 _tokenIndex) public constant returns (address);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public constant returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public constant returns (uint256);
}
/*
Bancor Gas Price Limit interface
*/
contract IBancorGasPriceLimit {
function gasPrice() public constant returns (uint256) {}
}
/*
Bancor Quick Converter interface
*/
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
}
/*
Bancor Converter Extensions interface
*/
contract IBancorConverterExtensions {
function formula() public constant returns (IBancorFormula) {}
function gasPriceLimit() public constant returns (IBancorGasPriceLimit) {}
function quickConverter() public constant returns (IBancorQuickConverter) {}
}
/*
The smart token controller is an upgradable part of the smart token that allows
more functionality as well as fixes for bugs/exploits.
Once it accepts ownership of the token, it becomes the token's sole controller
that can execute any of its functions.
To upgrade the controller, ownership must be transferred to a new controller, along with
any relevant data.
The smart token must be set on construction and cannot be changed afterwards.
Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access.
Note that the controller can transfer token ownership to a new controller that
doesn't allow executing any function on the token, for a trustless solution.
Doing that will also remove the owner's ability to upgrade the controller.
*/
contract SmartTokenController is TokenHolder {
ISmartToken public token; // smart token
/**
@dev constructor
*/
function SmartTokenController(ISmartToken _token)
validAddress(_token)
{
token = _token;
}
// ensures that the controller is the token's owner
modifier active() {
assert(token.owner() == address(this));
_;
}
// ensures that the controller is not the token's owner
modifier inactive() {
assert(token.owner() != address(this));
_;
}
/**
@dev allows transferring the token ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new token owner
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
/**
@dev used by a new owner to accept a token ownership transfer
can only be called by the contract owner
*/
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
/**
@dev disables/enables token transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
/**
@dev withdraws tokens held by the token and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawFromToken(IERC20Token _token, address _to, uint256 _amount) public ownerOnly {
ITokenHolder(token).withdrawTokens(_token, _to, _amount);
}
}
/*
Bancor Converter v0.6
The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves.
ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on
the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract.
The converter is upgradable (just like any SmartTokenController).
WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits
or with very small numbers because of precision loss
Open issues:
- Front-running attacks are currently mitigated by the following mechanisms:
- minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction
- gas price limit prevents users from having control over the order of execution
Other potential solutions might include a commit/reveal based schemes
- Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct
*/
contract BancorConverter is ITokenConverter, SmartTokenController, Managed {
uint32 private constant MAX_WEIGHT = 1000000;
uint32 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint256 virtualBalance; // connector virtual balance
uint32 weight; // connector weight, represented in ppm, 1-1000000
bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not
bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner
bool isSet; // used to tell if the mapping element is defined
}
string public version = '0.6';
string public converterType = 'bancor';
IBancorConverterExtensions public extensions; // bancor converter extensions contract
IERC20Token[] public connectorTokens; // ERC20 standard token addresses
IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH
mapping (address => Connector) public connectors; // connector token addresses -> connector data
uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100%
uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public conversionsEnabled = true; // true if token conversions is enabled, false if not
// triggered when a conversion between two tokens occurs (TokenConverter event)
event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
uint256 _currentPriceN, uint256 _currentPriceD);
// triggered when the conversion fee is updated
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
@dev constructor
@param _token smart token governed by the converter
@param _extensions address of a bancor converter extensions contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
*/
function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight)
SmartTokenController(_token)
validAddress(_extensions)
validMaxConversionFee(_maxConversionFee)
{
extensions = _extensions;
maxConversionFee = _maxConversionFee;
if (address(_connectorToken) != 0x0)
addConnector(_connectorToken, _connectorWeight, false);
}
// validates a connector token address - verifies that the address belongs to one of the connector tokens
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
// validates a token address - verifies that the address belongs to one of the convertible tokens
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
// verifies that the gas price is lower than the universal limit
modifier validGasPrice() {
assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice());
_;
}
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
_;
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
// validates connector weight range
modifier validConnectorWeight(uint32 _weight) {
require(_weight > 0 && _weight <= MAX_WEIGHT);
_;
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
// allows execution only when conversions aren't disabled
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
/**
@dev returns the number of connector tokens defined
@return number of connector tokens
*/
function connectorTokenCount() public constant returns (uint16) {
return uint16(connectorTokens.length);
}
/**
@dev returns the number of convertible tokens supported by the contract
note that the number of convertible tokens is the number of connector token, plus 1 (that represents the smart token)
@return number of convertible tokens
*/
function convertibleTokenCount() public constant returns (uint16) {
return connectorTokenCount() + 1;
}
/**
@dev given a convertible token index, returns its contract address
@param _tokenIndex convertible token index
@return convertible token address
*/
function convertibleToken(uint16 _tokenIndex) public constant returns (address) {
if (_tokenIndex == 0)
return token;
return connectorTokens[_tokenIndex - 1];
}
/*
@dev allows the owner to update the extensions contract address
@param _extensions address of a bancor converter extensions contract
*/
function setExtensions(IBancorConverterExtensions _extensions)
public
ownerOnly
validAddress(_extensions)
notThis(_extensions)
{
extensions = _extensions;
}
/*
@dev allows the manager to update the quick buy path
@param _path new quick buy path, see conversion path format in the BancorQuickConverter contract
*/
function setQuickBuyPath(IERC20Token[] _path)
public
ownerOnly
validConversionPath(_path)
{
quickBuyPath = _path;
}
/*
@dev allows the manager to clear the quick buy path
*/
function clearQuickBuyPath() public ownerOnly {
quickBuyPath.length = 0;
}
/**
@dev returns the length of the quick buy path array
@return quick buy path length
*/
function getQuickBuyPathLength() public constant returns (uint256) {
return quickBuyPath.length;
}
/**
@dev disables the entire conversion functionality
this is a safety mechanism in case of a emergency
can only be called by the manager
@param _disable true to disable conversions, false to re-enable them
*/
function disableConversions(bool _disable) public managerOnly {
conversionsEnabled = !_disable;
}
/**
@dev updates the current conversion fee
can only be called by the manager
@param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee)
public
managerOnly
validConversionFee(_conversionFee)
{
ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/*
@dev returns the conversion fee amount for a given return amount
@return conversion fee amount
*/
function getConversionFeeAmount(uint256 _amount) public constant returns (uint256) {
return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE;
}
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
*/
function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input
connectors[_token].virtualBalance = 0;
connectors[_token].weight = _weight;
connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
connectors[_token].isPurchaseEnabled = true;
connectors[_token].isSet = true;
connectorTokens.push(_token);
totalConnectorWeight += _weight;
}
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
@param _virtualBalance new connector's virtual balance
*/
function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input
totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
connector.weight = _weight;
connector.isVirtualBalanceEnabled = _enableVirtualBalance;
connector.virtualBalance = _virtualBalance;
}
/**
@dev disables purchasing with the given connector token in case the connector token got compromised
can only be called by the owner
note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
@param _connectorToken connector token contract address
@param _disable true to disable the token, false to re-enable it
*/
function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
public
ownerOnly
validConnector(_connectorToken)
{
connectors[_connectorToken].isPurchaseEnabled = !_disable;
}
/**
@dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
@param _connectorToken connector token contract address
@return connector balance
*/
function getConnectorBalance(IERC20Token _connectorToken)
public
constant
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
}
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 connectors
uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
}
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
constant
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled); // validate input
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public constant returns (uint256) {
return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply());
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
// conversion between 2 connectors
uint256 purchaseAmount = buy(_fromToken, _amount, 1);
return sell(_toToken, purchaseAmount, _minReturn);
}
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return buy return amount
*/
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
assert(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
// transfer _depositAmount funds from the caller in the connector token
assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
dispatchConversionEvent(_connectorToken, _depositAmount, amount, true);
return amount;
}
/**
@dev sells the token by withdrawing from one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
@return sell return amount
*/
function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
uint256 amount = getSaleReturn(_connectorToken, _sellAmount);
assert(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
// ensure that the trade will only deplete the connector if the total supply is depleted as well
assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, amount);
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
assert(_connectorToken.transfer(msg.sender, amount));
dispatchConversionEvent(_connectorToken, _sellAmount, amount, false);
return amount;
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorQuickConverter contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
public
payable
validConversionPath(_path)
returns (uint256)
{
IERC20Token fromToken = _path[0];
IBancorQuickConverter quickConverter = extensions.quickConverter();
// we need to transfer the source tokens from the caller to the quick converter,
// so it can execute the conversion on behalf of the caller
if (msg.value == 0) {
// not ETH, send the source tokens to the quick converter
// if the token is the smart token, no allowance is required - destroy the tokens from the caller and issue them to the quick converter
if (fromToken == token) {
token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
token.issue(quickConverter, _amount); // issue _amount new tokens to the quick converter
}
else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the quick converter
assert(fromToken.transferFrom(msg.sender, quickConverter, _amount));
}
}
// execute the conversion and pass on the ETH with the call
return quickConverter.convertFor.value(msg.value)(_path, _amount, _minReturn, msg.sender);
}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convert(_fromToken, _toToken, _amount, _minReturn);
}
/**
@dev utility, returns the expected return for selling the token for one of its connector tokens, given a total supply override
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _totalSupply total token supply, overrides the actual token total supply when calculating the return
@return sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _totalSupply)
private
constant
active
validConnector(_connectorToken)
greaterThanZero(_totalSupply)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev helper, dispatches the Conversion event
The function also takes the tokens' decimals into account when calculating the current price
@param _connectorToken connector token contract address
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
@param isPurchase true if it's a purchase, false if it's a sale
*/
function dispatchConversionEvent(IERC20Token _connectorToken, uint256 _amount, uint256 _returnAmount, bool isPurchase) private {
Connector storage connector = connectors[_connectorToken];
// calculate the new price using the simple price formula
// price = connector balance / (supply * weight)
// weight is represented in ppm, so multiplying by 1000000
uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT);
uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight);
// normalize values
uint8 tokenDecimals = token.decimals();
uint8 connectorTokenDecimals = _connectorToken.decimals();
if (tokenDecimals != connectorTokenDecimals) {
if (tokenDecimals > connectorTokenDecimals)
connectorAmount = safeMul(connectorAmount, 10 ** uint256(tokenDecimals - connectorTokenDecimals));
else
tokenAmount = safeMul(tokenAmount, 10 ** uint256(connectorTokenDecimals - tokenDecimals));
}
if (isPurchase)
Conversion(_connectorToken, token, msg.sender, _amount, _returnAmount, connectorAmount, tokenAmount);
else
Conversion(token, _connectorToken, msg.sender, _amount, _returnAmount, tokenAmount, connectorAmount);
}
/**
@dev fallback, buys the smart token with ETH
note that the purchase will use the price at the time of the purchase
*/
function() payable {
quickConvert(quickBuyPath, msg.value, 1);
}
}File 2 of 10: BancorQuickConverter
pragma solidity ^0.4.11;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) {}
function symbol() public constant returns (string) {}
function decimals() public constant returns (uint8) {}
function totalSupply() public constant returns (uint256) {}
function balanceOf(address _owner) public constant returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
Ether Token interface
*/
contract IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint256 _amount) public;
function withdrawTo(address _to, uint256 _amount);
}
/*
EIP228 Token Converter interface
*/
contract ITokenConverter {
function convertibleTokenCount() public constant returns (uint16);
function convertibleToken(uint16 _tokenIndex) public constant returns (address);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
/*
Bancor Quick Converter interface
*/
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
}
/*
The BancorQuickConverter contract provides allows converting between any token in the
bancor network in a single transaction.
A note on conversion paths -
Conversion path is a data structure that's used when converting a token to another token in the bancor network
when the conversion cannot necessarily be done by single converter and might require multiple 'hops'.
The path defines which converters should be used and what kind of conversion should be done in each step.
The path format doesn't include complex structure and instead, it is represented by a single array
in which each 'hop' is represented by a 2-tuple - smart token & to token.
In addition, the first element is always the source token.
The smart token is only used as a pointer to a converter (since converter addresses are more likely to change).
Format:
[source token, smart token, to token, smart token, to token...]
*/
contract BancorQuickConverter is IBancorQuickConverter, TokenHolder {
mapping (address => bool) public etherTokens; // list of all supported ether tokens
/**
@dev constructor
*/
function BancorQuickConverter() {
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
/**
@dev allows the owner to register/unregister ether tokens
@param _token ether token contract address
@param _register true to register, false to unregister
*/
function registerEtherToken(IEtherToken _token, bool _register)
public
ownerOnly
validAddress(_token)
notThis(_token)
{
etherTokens[_token] = _register;
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens to a target account
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for)
public
payable
validConversionPath(_path)
returns (uint256)
{
// if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token
IERC20Token fromToken = _path[0];
require(msg.value == 0 || (_amount == msg.value && etherTokens[fromToken]));
ISmartToken smartToken;
IERC20Token toToken;
ITokenConverter converter;
uint256 pathLength = _path.length;
// if ETH was sent with the call, the source is an ether token - deposit the ETH in it
// otherwise, we assume we already have the tokens
if (msg.value > 0)
IEtherToken(fromToken).deposit.value(msg.value)();
// iterate over the conversion path
for (uint256 i = 1; i < pathLength; i += 2) {
smartToken = ISmartToken(_path[i]);
toToken = _path[i + 1];
converter = ITokenConverter(smartToken.owner());
// if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request
if (smartToken != fromToken)
ensureAllowance(fromToken, converter, _amount);
// make the conversion - if it's the last one, also provide the minimum return value
_amount = converter.change(fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1);
fromToken = toToken;
}
// finished the conversion, transfer the funds to the target account
// if the target token is an ether token, withdraw the tokens and send them as ETH
// otherwise, transfer the tokens as is
if (etherTokens[toToken])
IEtherToken(toToken).withdrawTo(_for, _amount);
else
assert(toToken.transfer(_for, _amount));
return _amount;
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens to a target account
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) {
// we need to transfer the tokens from the caller to the converter before we follow
// the conversion path, to allow it to execute the conversion on behalf of the caller
// note: we assume we already have allowance
IERC20Token fromToken = _path[0];
assert(fromToken.transferFrom(msg.sender, this, _amount));
return convertFor(_path, _amount, _minReturn, _for);
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens back to the sender
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) {
return convertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens back to the sender
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return claimAndConvertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev utility, checks whether allowance for the given spender exists and approves one if it doesn't
@param _token token to check the allowance in
@param _spender approved address
@param _value allowance amount
*/
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private {
// check if allowance for the given amount already exists
if (_token.allowance(this, _spender) >= _value)
return;
// if the allowance is nonzero, must reset it to 0 first
if (_token.allowance(this, _spender) != 0)
assert(_token.approve(_spender, 0));
// approve the new allowance
assert(_token.approve(_spender, _value));
}
}File 3 of 10: DSToken
pragma solidity ^0.4.13;
////// lib/ds-math/src/math.sol
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.4.13; */
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
////// lib/ds-stop/lib/ds-auth/src/auth.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.4.13; */
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
////// lib/ds-stop/lib/ds-note/src/note.sol
/// note.sol -- the `note' modifier, for logging calls as events
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.4.13; */
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
////// lib/ds-stop/src/stop.sol
/// stop.sol -- mixin for enable/disable functionality
// Copyright (C) 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.4.13; */
/* import "ds-auth/auth.sol"; */
/* import "ds-note/note.sol"; */
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
////// lib/erc20/src/erc20.sol
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
// This file likely does not meet the threshold of originality
// required for copyright to apply. As a result, this is free and
// unencumbered software belonging to the public domain.
/* pragma solidity ^0.4.8; */
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
////// src/base.sol
/// base.sol -- basic ERC20 implementation
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.4.13; */
/* import "erc20/erc20.sol"; */
/* import "ds-math/math.sol"; */
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
function DSTokenBase(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
}
////// src/token.sol
/// token.sol -- ERC20 implementation with minting and burning
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.4.13; */
/* import "ds-stop/stop.sol"; */
/* import "./base.sol"; */
contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
function DSToken(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
Burn(guy, wad);
}
// Optional token name
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}File 4 of 10: SmartToken
pragma solidity ^0.4.11;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal constant returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal constant returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal constant returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) {}
function symbol() public constant returns (string) {}
function decimals() public constant returns (uint8) {}
function totalSupply() public constant returns (uint256) {}
function balanceOf(address _owner) public constant returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/*
Smart Token v0.3
'Owned' is specified here for readability reasons
*/
contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
string public version = '0.3';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
@param _name token name
@param _symbol token short symbol, minimum 1 character
@param _decimals for display purposes only
*/
function SmartToken(string _name, string _symbol, uint8 _decimals)
ERC20Token(_name, _symbol, _decimals)
{
NewSmartToken(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
@dev disables/enables transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract owner
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
Issuance(_amount);
Transfer(this, _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) public {
require(msg.sender == _from || msg.sender == owner); // validate input
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
}File 5 of 10: SmartToken
pragma solidity ^0.4.11;
/*
Overflow protected math functions
*/
contract SafeMath {
/**
constructor
*/
function SafeMath() {
}
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address owner) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned {
/**
@dev constructor
*/
function TokenHolder() {
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string name) { name; }
function symbol() public constant returns (string symbol) { symbol; }
function decimals() public constant returns (uint8 decimals) { decimals; }
function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, SafeMath {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/*
Smart Token interface
*/
contract ISmartToken is ITokenHolder, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/*
Smart Token v0.2
'Owned' is specified here for readability reasons
*/
contract SmartToken is ISmartToken, ERC20Token, Owned, TokenHolder {
string public version = '0.2';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
@param _name token name
@param _symbol token short symbol, 1-6 characters
@param _decimals for display purposes only
*/
function SmartToken(string _name, string _symbol, uint8 _decimals)
ERC20Token(_name, _symbol, _decimals)
{
require(bytes(_symbol).length <= 6); // validate input
NewSmartToken(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
@dev disables/enables transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract owner
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
Issuance(_amount);
Transfer(this, _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can only be called by the contract owner
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount)
public
ownerOnly
{
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
note that when transferring to the smart token's address, the coins are actually destroyed
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
// transferring to the contract address destroys tokens
if (_to == address(this)) {
balanceOf[_to] -= _value;
totalSupply -= _value;
Destruction(_value);
}
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
note that when transferring to the smart token's address, the coins are actually destroyed
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
// transferring to the contract address destroys tokens
if (_to == address(this)) {
balanceOf[_to] -= _value;
totalSupply -= _value;
Destruction(_value);
}
return true;
}
}File 6 of 10: BancorConverter
pragma solidity ^0.4.18;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Provides support and utilities for contract management
*/
contract Managed {
address public manager;
address public newManager;
event ManagerUpdate(address indexed _prevManager, address indexed _newManager);
/**
@dev constructor
*/
function Managed() public {
manager = msg.sender;
}
// allows execution by the manager only
modifier managerOnly {
assert(msg.sender == manager);
_;
}
/**
@dev allows transferring the contract management
the new manager still needs to accept the transfer
can only be called by the contract manager
@param _newManager new contract manager
*/
function transferManagement(address _newManager) public managerOnly {
require(_newManager != manager);
newManager = _newManager;
}
/**
@dev used by a new manager to accept a management transfer
*/
function acceptManagement() public {
require(msg.sender == newManager);
ManagerUpdate(manager, newManager);
manager = newManager;
newManager = address(0);
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
@dev constructor
*/
function Owned() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() public {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
Ether Token interface
*/
contract IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint256 _amount) public;
function withdrawTo(address _to, uint256 _amount) public;
}
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/*
The smart token controller is an upgradable part of the smart token that allows
more functionality as well as fixes for bugs/exploits.
Once it accepts ownership of the token, it becomes the token's sole controller
that can execute any of its functions.
To upgrade the controller, ownership must be transferred to a new controller, along with
any relevant data.
The smart token must be set on construction and cannot be changed afterwards.
Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access.
Note that the controller can transfer token ownership to a new controller that
doesn't allow executing any function on the token, for a trustless solution.
Doing that will also remove the owner's ability to upgrade the controller.
*/
contract SmartTokenController is TokenHolder {
ISmartToken public token; // smart token
/**
@dev constructor
*/
function SmartTokenController(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
// ensures that the controller is the token's owner
modifier active() {
assert(token.owner() == address(this));
_;
}
// ensures that the controller is not the token's owner
modifier inactive() {
assert(token.owner() != address(this));
_;
}
/**
@dev allows transferring the token ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new token owner
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
/**
@dev used by a new owner to accept a token ownership transfer
can only be called by the contract owner
*/
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
/**
@dev disables/enables token transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
/**
@dev withdraws tokens held by the controller and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawFromToken(
IERC20Token _token,
address _to,
uint256 _amount
)
public
ownerOnly
{
ITokenHolder(token).withdrawTokens(_token, _to, _amount);
}
}
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
}
/*
Bancor Gas Price Limit interface
*/
contract IBancorGasPriceLimit {
function gasPrice() public view returns (uint256) {}
}
/*
Bancor Quick Converter interface
*/
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
}
/*
Bancor Converter Extensions interface
*/
contract IBancorConverterExtensions {
function formula() public view returns (IBancorFormula) {}
function gasPriceLimit() public view returns (IBancorGasPriceLimit) {}
function quickConverter() public view returns (IBancorQuickConverter) {}
}
/*
EIP228 Token Converter interface
*/
contract ITokenConverter {
function convertibleTokenCount() public view returns (uint16);
function convertibleToken(uint16 _tokenIndex) public view returns (address);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
/*
Bancor Converter v0.7
The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves.
ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on
the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract.
The converter is upgradable (just like any SmartTokenController).
WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits
or with very small numbers because of precision loss
Open issues:
- Front-running attacks are currently mitigated by the following mechanisms:
- minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction
- gas price limit prevents users from having control over the order of execution
Other potential solutions might include a commit/reveal based schemes
- Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct
*/
contract BancorConverter is ITokenConverter, SmartTokenController, Managed {
uint32 private constant MAX_WEIGHT = 1000000;
uint32 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint256 virtualBalance; // connector virtual balance
uint32 weight; // connector weight, represented in ppm, 1-1000000
bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not
bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner
bool isSet; // used to tell if the mapping element is defined
}
string public version = '0.7';
string public converterType = 'bancor';
IBancorConverterExtensions public extensions; // bancor converter extensions contract
IERC20Token[] public connectorTokens; // ERC20 standard token addresses
IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH
mapping (address => Connector) public connectors; // connector token addresses -> connector data
uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100%
uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public conversionsEnabled = true; // true if token conversions is enabled, false if not
// triggered when a conversion between two tokens occurs (TokenConverter event)
event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
int256 _conversionFee, uint256 _currentPriceN, uint256 _currentPriceD);
// triggered when the conversion fee is updated
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
@dev constructor
@param _token smart token governed by the converter
@param _extensions address of a bancor converter extensions contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
*/
function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight)
public
SmartTokenController(_token)
validAddress(_extensions)
validMaxConversionFee(_maxConversionFee)
{
extensions = _extensions;
maxConversionFee = _maxConversionFee;
if (_connectorToken != address(0))
addConnector(_connectorToken, _connectorWeight, false);
}
// validates a connector token address - verifies that the address belongs to one of the connector tokens
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
// validates a token address - verifies that the address belongs to one of the convertible tokens
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
// verifies that the gas price is lower than the universal limit
modifier validGasPrice() {
assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice());
_;
}
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
_;
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
// validates connector weight range
modifier validConnectorWeight(uint32 _weight) {
require(_weight > 0 && _weight <= MAX_WEIGHT);
_;
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
// allows execution only when conversions aren't disabled
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
// allows execution only for owner or manager
modifier ownerOrManagerOnly {
require(msg.sender == owner || msg.sender == manager);
_;
}
/**
@dev returns the number of connector tokens defined
@return number of connector tokens
*/
function connectorTokenCount() public view returns (uint16) {
return uint16(connectorTokens.length);
}
/**
@dev returns the number of convertible tokens supported by the contract
note that the number of convertible tokens is the number of connector token, plus 1 (that represents the smart token)
@return number of convertible tokens
*/
function convertibleTokenCount() public view returns (uint16) {
return connectorTokenCount() + 1;
}
/**
@dev given a convertible token index, returns its contract address
@param _tokenIndex convertible token index
@return convertible token address
*/
function convertibleToken(uint16 _tokenIndex) public view returns (address) {
if (_tokenIndex == 0)
return token;
return connectorTokens[_tokenIndex - 1];
}
/*
@dev allows the owner to update the extensions contract address
@param _extensions address of a bancor converter extensions contract
*/
function setExtensions(IBancorConverterExtensions _extensions)
public
ownerOnly
validAddress(_extensions)
notThis(_extensions)
{
extensions = _extensions;
}
/*
@dev allows the manager to update the quick buy path
@param _path new quick buy path, see conversion path format in the BancorQuickConverter contract
*/
function setQuickBuyPath(IERC20Token[] _path)
public
ownerOnly
validConversionPath(_path)
{
quickBuyPath = _path;
}
/*
@dev allows the manager to clear the quick buy path
*/
function clearQuickBuyPath() public ownerOnly {
quickBuyPath.length = 0;
}
/**
@dev returns the length of the quick buy path array
@return quick buy path length
*/
function getQuickBuyPathLength() public view returns (uint256) {
return quickBuyPath.length;
}
/**
@dev disables the entire conversion functionality
this is a safety mechanism in case of a emergency
can only be called by the manager
@param _disable true to disable conversions, false to re-enable them
*/
function disableConversions(bool _disable) public ownerOrManagerOnly {
conversionsEnabled = !_disable;
}
/**
@dev updates the current conversion fee
can only be called by the manager
@param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee)
public
ownerOrManagerOnly
validConversionFee(_conversionFee)
{
ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/*
@dev returns the conversion fee amount for a given return amount
@return conversion fee amount
*/
function getConversionFeeAmount(uint256 _amount) public view returns (uint256) {
return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE;
}
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
*/
function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input
connectors[_token].virtualBalance = 0;
connectors[_token].weight = _weight;
connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
connectors[_token].isPurchaseEnabled = true;
connectors[_token].isSet = true;
connectorTokens.push(_token);
totalConnectorWeight += _weight;
}
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
@param _virtualBalance new connector's virtual balance
*/
function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input
totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
connector.weight = _weight;
connector.isVirtualBalanceEnabled = _enableVirtualBalance;
connector.virtualBalance = _virtualBalance;
}
/**
@dev disables purchasing with the given connector token in case the connector token got compromised
can only be called by the owner
note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
@param _connectorToken connector token contract address
@param _disable true to disable the token, false to re-enable it
*/
function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
public
ownerOnly
validConnector(_connectorToken)
{
connectors[_connectorToken].isPurchaseEnabled = !_disable;
}
/**
@dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
@param _connectorToken connector token contract address
@return connector balance
*/
function getConnectorBalance(IERC20Token _connectorToken)
public
view
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
}
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 connectors
uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
}
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled); // validate input
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view returns (uint256) {
return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply());
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
// conversion between 2 connectors
uint256 purchaseAmount = buy(_fromToken, _amount, 1);
return sell(_toToken, purchaseAmount, _minReturn);
}
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return buy return amount
*/
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
require(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
// transfer _depositAmount funds from the caller in the connector token
assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
dispatchConversionEvent(_connectorToken, _depositAmount, amount, true);
return amount;
}
/**
@dev sells the token by withdrawing from one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
@return sell return amount
*/
function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
uint256 amount = getSaleReturn(_connectorToken, _sellAmount);
require(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
// ensure that the trade will only deplete the connector if the total supply is depleted as well
assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, amount);
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
assert(_connectorToken.transfer(msg.sender, amount));
dispatchConversionEvent(_connectorToken, _sellAmount, amount, false);
return amount;
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorQuickConverter contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
public
payable
validConversionPath(_path)
returns (uint256)
{
IERC20Token fromToken = _path[0];
IBancorQuickConverter quickConverter = extensions.quickConverter();
// we need to transfer the source tokens from the caller to the quick converter,
// so it can execute the conversion on behalf of the caller
if (msg.value == 0) {
// not ETH, send the source tokens to the quick converter
// if the token is the smart token, no allowance is required - destroy the tokens from the caller and issue them to the quick converter
if (fromToken == token) {
token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
token.issue(quickConverter, _amount); // issue _amount new tokens to the quick converter
}
else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the quick converter
assert(fromToken.transferFrom(msg.sender, quickConverter, _amount));
}
}
// execute the conversion and pass on the ETH with the call
return quickConverter.convertFor.value(msg.value)(_path, _amount, _minReturn, msg.sender);
}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convert(_fromToken, _toToken, _amount, _minReturn);
}
/**
@dev utility, returns the expected return for selling the token for one of its connector tokens, given a total supply override
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _totalSupply total token supply, overrides the actual token total supply when calculating the return
@return sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _totalSupply)
private
view
active
validConnector(_connectorToken)
greaterThanZero(_totalSupply)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev helper, dispatches the Conversion event
The function also takes the tokens' decimals into account when calculating the current price
@param _connectorToken connector token contract address
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
@param isPurchase true if it's a purchase, false if it's a sale
*/
function dispatchConversionEvent(IERC20Token _connectorToken, uint256 _amount, uint256 _returnAmount, bool isPurchase) private {
Connector storage connector = connectors[_connectorToken];
// calculate the new price using the simple price formula
// price = connector balance / (supply * weight)
// weight is represented in ppm, so multiplying by 1000000
uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT);
uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight);
// normalize values
uint8 tokenDecimals = token.decimals();
uint8 connectorTokenDecimals = _connectorToken.decimals();
if (tokenDecimals != connectorTokenDecimals) {
if (tokenDecimals > connectorTokenDecimals)
connectorAmount = safeMul(connectorAmount, 10 ** uint256(tokenDecimals - connectorTokenDecimals));
else
tokenAmount = safeMul(tokenAmount, 10 ** uint256(connectorTokenDecimals - tokenDecimals));
}
uint256 feeAmount = getConversionFeeAmount(_returnAmount);
// ensure that the fee is capped at 255 bits to prevent overflow when converting it to a signed int
assert(feeAmount <= 2 ** 255);
if (isPurchase)
Conversion(_connectorToken, token, msg.sender, _amount, _returnAmount, int256(feeAmount), connectorAmount, tokenAmount);
else
Conversion(token, _connectorToken, msg.sender, _amount, _returnAmount, int256(feeAmount), tokenAmount, connectorAmount);
}
/**
@dev fallback, buys the smart token with ETH
note that the purchase will use the price at the time of the purchase
*/
function() payable public {
quickConvert(quickBuyPath, msg.value, 1);
}
}File 7 of 10: EtherToken
pragma solidity ^0.4.11;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address owner) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string name) { name; }
function symbol() public constant returns (string symbol) { symbol; }
function decimals() public constant returns (uint8 decimals) { decimals; }
function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/*
Ether Token interface
*/
contract IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint256 _amount) public;
function withdrawTo(address _to, uint256 _amount);
}
/**
Ether tokenization contract
'Owned' is specified here for readability reasons
*/
contract EtherToken is IEtherToken, Owned, ERC20Token, TokenHolder {
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
*/
function EtherToken()
ERC20Token('Ether Token', 'ETH', 18) {
}
/**
@dev deposit ether in the account
*/
function deposit() public payable {
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], msg.value); // add the value to the account balance
totalSupply = safeAdd(totalSupply, msg.value); // increase the total supply
Issuance(msg.value);
Transfer(this, msg.sender, msg.value);
}
/**
@dev withdraw ether from the account
@param _amount amount of ether to withdraw
*/
function withdraw(uint256 _amount) public {
withdrawTo(msg.sender, _amount);
}
/**
@dev withdraw ether from the account to a target account
@param _to account to receive the ether
@param _amount amount of ether to withdraw
*/
function withdrawTo(address _to, uint256 _amount)
public
notThis(_to)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount); // deduct the amount from the account balance
totalSupply = safeSub(totalSupply, _amount); // decrease the total supply
_to.transfer(_amount); // send the amount to the target account
Transfer(msg.sender, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra protection
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transferFrom(_from, _to, _value));
return true;
}
/**
@dev deposit ether in the account
*/
function() public payable {
deposit();
}
}File 8 of 10: BancorConverterExtensions
pragma solidity ^0.4.11;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) {}
function symbol() public constant returns (string) {}
function decimals() public constant returns (uint8) {}
function totalSupply() public constant returns (uint256) {}
function balanceOf(address _owner) public constant returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public constant returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public constant returns (uint256);
}
/*
Bancor Gas Price Limit interface
*/
contract IBancorGasPriceLimit {
function gasPrice() public constant returns (uint256) {}
}
/*
Bancor Quick Converter interface
*/
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
Bancor Converter Extensions interface
*/
contract IBancorConverterExtensions {
function formula() public constant returns (IBancorFormula) {}
function gasPriceLimit() public constant returns (IBancorGasPriceLimit) {}
function quickConverter() public constant returns (IBancorQuickConverter) {}
}
/**
@dev the BancorConverterExtensions contract is an owned contract that serves as a single point of access
to the BancorFormula, BancorGasPriceLimit and BancorQuickConverter contracts from all BancorConverter contract instances.
it allows upgrading these contracts without the need to update each and every
BancorConverter contract instance individually.
*/
contract BancorConverterExtensions is IBancorConverterExtensions, TokenHolder {
IBancorFormula public formula; // bancor calculation formula contract
IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract
IBancorQuickConverter public quickConverter; // bancor quick converter contract
/**
@dev constructor
@param _formula address of a bancor formula contract
@param _gasPriceLimit address of a bancor gas price limit contract
@param _quickConverter address of a bancor quick converter contract
*/
function BancorConverterExtensions(IBancorFormula _formula, IBancorGasPriceLimit _gasPriceLimit, IBancorQuickConverter _quickConverter)
validAddress(_formula)
validAddress(_gasPriceLimit)
validAddress(_quickConverter)
{
formula = _formula;
gasPriceLimit = _gasPriceLimit;
quickConverter = _quickConverter;
}
/*
@dev allows the owner to update the formula contract address
@param _formula address of a bancor formula contract
*/
function setFormula(IBancorFormula _formula)
public
ownerOnly
validAddress(_formula)
notThis(_formula)
{
formula = _formula;
}
/*
@dev allows the owner to update the gas price limit contract address
@param _gasPriceLimit address of a bancor gas price limit contract
*/
function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit)
public
ownerOnly
validAddress(_gasPriceLimit)
notThis(_gasPriceLimit)
{
gasPriceLimit = _gasPriceLimit;
}
/*
@dev allows the owner to update the quick converter contract address
@param _quickConverter address of a bancor quick converter contract
*/
function setQuickConverter(IBancorQuickConverter _quickConverter)
public
ownerOnly
validAddress(_quickConverter)
notThis(_quickConverter)
{
quickConverter = _quickConverter;
}
}File 9 of 10: BancorGasPriceLimit
pragma solidity ^0.4.18;
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
@dev constructor
*/
function Owned() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Bancor Gas Price Limit interface
*/
contract IBancorGasPriceLimit {
function gasPrice() public view returns (uint256) {}
}
/*
The BancorGasPriceLimit contract serves as an extra front-running attack mitigation mechanism.
It sets a maximum gas price on all bancor conversions, which prevents users from "cutting in line"
in order to front-run other transactions.
The gas price limit is universal to all converters and it can be updated by the owner to be in line
with the network's current gas price.
*/
contract BancorGasPriceLimit is IBancorGasPriceLimit, Owned, Utils {
uint256 public gasPrice = 0 wei; // maximum gas price for bancor transactions
/**
@dev constructor
@param _gasPrice gas price limit
*/
function BancorGasPriceLimit(uint256 _gasPrice)
public
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
/*
@dev gas price getter
@return the current gas price
*/
function gasPrice() public view returns (uint256) {
validateGasPrice(tx.gasprice);
return gasPrice;
}
/*
@dev allows the owner to update the gas price limit
@param _gasPrice new gas price limit
*/
function setGasPrice(uint256 _gasPrice)
public
ownerOnly
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
/*
@dev validate that the given gas price is equal to the current network gas price
@param _gasPrice tested gas price
*/
function validateGasPrice(uint256 _gasPrice)
public
view
greaterThanZero(_gasPrice)
{
require(_gasPrice == gasPrice);
}
}File 10 of 10: BancorFormula
pragma solidity ^0.4.11;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public constant returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public constant returns (uint256);
}
contract BancorFormula is IBancorFormula, Utils {
string public version = '0.2';
uint32 private constant MAX_CRR = 1000000;
uint256 private constant ONE = 1;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below.
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x1ffffffffffffffffffffffffffffffff;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintLn2ScalingFactors.py', run it and paste the results below.
*/
uint256 private constant LN2_MANTISSA = 0x2c5c85fdf473de6af278ece600fcbda;
uint8 private constant LN2_EXPONENT = 122;
/**
The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them:
Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below.
*/
uint256[128] private maxExpArray;
function BancorFormula() {
// maxExpArray[ 0] = 0x60ffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x5ebfffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x5cbfffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5abfffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x58dfffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x56ffffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x006ae67b5f2f528d5f3189036ee0f27453;
}
/**
@dev given a token supply, reserve, CRR and a deposit amount (in the reserve token), calculates the return for a given change (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 1000000) - 1)
@param _supply token total supply
@param _reserveBalance total reserve
@param _reserveRatio constant reserve ratio, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in reserve token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public constant returns (uint256) {
// validate input
require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_CRR);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the CRR = 100%
if (_reserveRatio == MAX_CRR)
return safeMul(_supply, _depositAmount) / _reserveBalance;
uint256 baseN = safeAdd(_depositAmount, _reserveBalance);
var (result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_CRR);
uint256 temp = safeMul(_supply, result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, reserve, CRR and a sell amount (in the main token), calculates the return for a given change (in the reserve token)
Formula:
Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / 1000000)))
@param _supply token total supply
@param _reserveBalance total reserve
@param _reserveRatio constant reserve ratio, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public constant returns (uint256) {
// validate input
require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_CRR && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _reserveBalance;
// special case if the CRR = 100%
if (_reserveRatio == MAX_CRR)
return safeMul(_reserveBalance, _sellAmount) / _supply;
uint256 baseD = _supply - _sellAmount;
var (result, precision) = power(_supply, baseD, MAX_CRR, _reserveRatio);
uint256 temp1 = safeMul(_reserveBalance, result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (ln(base) * exp)".
The value of "ln(base)" is represented with an integer slightly smaller than "ln(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal constant returns (uint256, uint8) {
uint256 lnBaseTimesExp = ln(_baseN, _baseD) * _expN / _expD;
uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
return (fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
/**
Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:
- The numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The output is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
*/
function ln(uint256 _numerator, uint256 _denominator) internal constant returns (uint256) {
assert(_numerator <= MAX_NUM);
uint256 res = 0;
uint256 x = _numerator * FIXED_1 / _denominator;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return (res * LN2_MANTISSA) >> LN2_EXPONENT;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal constant returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal constant returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
assert(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionFixedExp.py'.
It approximates "e ^ x" via maclauren summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x >> precision) << precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function fixedExp(uint256 _x, uint8 _precision) internal constant returns (uint256) {
uint256 xi = _x;
uint256 res = uint256(0xde1bc4d19efcac82445da75b00000000) << _precision;
res += xi * 0xde1bc4d19efcac82445da75b00000000;
xi = (xi * _x) >> _precision;
res += xi * 0x6f0de268cf7e5641222ed3ad80000000;
xi = (xi * _x) >> _precision;
res += xi * 0x2504a0cd9a7f7215b60f9be480000000;
xi = (xi * _x) >> _precision;
res += xi * 0x9412833669fdc856d83e6f920000000;
xi = (xi * _x) >> _precision;
res += xi * 0x1d9d4d714865f4de2b3fafea0000000;
xi = (xi * _x) >> _precision;
res += xi * 0x4ef8ce836bba8cfb1dff2a70000000;
xi = (xi * _x) >> _precision;
res += xi * 0xb481d807d1aa66d04490610000000;
xi = (xi * _x) >> _precision;
res += xi * 0x16903b00fa354cda08920c2000000;
xi = (xi * _x) >> _precision;
res += xi * 0x281cdaac677b334ab9e732000000;
xi = (xi * _x) >> _precision;
res += xi * 0x402e2aad725eb8778fd85000000;
xi = (xi * _x) >> _precision;
res += xi * 0x5d5a6c9f31fe2396a2af000000;
xi = (xi * _x) >> _precision;
res += xi * 0x7c7890d442a82f73839400000;
xi = (xi * _x) >> _precision;
res += xi * 0x9931ed54034526b58e400000;
xi = (xi * _x) >> _precision;
res += xi * 0xaf147cf24ce150cf7e00000;
xi = (xi * _x) >> _precision;
res += xi * 0xbac08546b867cdaa200000;
xi = (xi * _x) >> _precision;
res += xi * 0xbac08546b867cdaa20000;
xi = (xi * _x) >> _precision;
res += xi * 0xafc441338061b2820000;
xi = (xi * _x) >> _precision;
res += xi * 0x9c3cabbc0056d790000;
xi = (xi * _x) >> _precision;
res += xi * 0x839168328705c30000;
xi = (xi * _x) >> _precision;
res += xi * 0x694120286c049c000;
xi = (xi * _x) >> _precision;
res += xi * 0x50319e98b3d2c000;
xi = (xi * _x) >> _precision;
res += xi * 0x3a52a1e36b82000;
xi = (xi * _x) >> _precision;
res += xi * 0x289286e0fce000;
xi = (xi * _x) >> _precision;
res += xi * 0x1b0c59eb53400;
xi = (xi * _x) >> _precision;
res += xi * 0x114f95b55400;
xi = (xi * _x) >> _precision;
res += xi * 0xaa7210d200;
xi = (xi * _x) >> _precision;
res += xi * 0x650139600;
xi = (xi * _x) >> _precision;
res += xi * 0x39b78e80;
xi = (xi * _x) >> _precision;
res += xi * 0x1fd8080;
xi = (xi * _x) >> _precision;
res += xi * 0x10fbc0;
xi = (xi * _x) >> _precision;
res += xi * 0x8c40;
xi = (xi * _x) >> _precision;
res += xi * 0x462;
xi = (xi * _x) >> _precision;
res += xi * 0x22;
return res / 0xde1bc4d19efcac82445da75b00000000;
}
}