Transaction Hash:
Block:
9745200 at Mar-26-2020 06:01:47 AM +UTC
Transaction Fee:
0.0018567971072 ETH
$3.47
Gas Used:
331,520 Gas / 5.60086 Gwei
Emitted Events:
100 |
EtherToken.Issuance( _amount=1787491802285946880 )
|
101 |
EtherToken.Transfer( _from=EtherToken, _to=BancorNetwork, _value=1787491802285946880 )
|
102 |
EtherToken.Approval( _owner=BancorNetwork, _spender=BancorConverter, _value=1787491802285946880 )
|
103 |
EtherToken.Transfer( _from=BancorNetwork, _to=BancorConverter, _value=1787491802285946880 )
|
104 |
SmartToken.Transfer( _from=BancorConverter, _to=BancorNetwork, _value=1391114106804432909457 )
|
105 |
BancorConverter.Conversion( _fromToken=EtherToken, _toToken=SmartToken, _trader=BancorNetwork, _amount=1787491802285946880, _return=1391114106804432909457, _conversionFee=2786407127349633303 )
|
106 |
BancorConverter.PriceDataUpdate( _connectorToken=EtherToken, _tokenSupply=13380718715135400766768310, _connectorBalance=11111130492705942242694, _connectorWeight=500000 )
|
107 |
BancorConverter.PriceDataUpdate( _connectorToken=SmartToken, _tokenSupply=13380718715135400766768310, _connectorBalance=8663157995622937583071858, _connectorWeight=500000 )
|
108 |
BancorNetwork.Conversion( _smartToken=SmartToken, _fromToken=EtherToken, _toToken=SmartToken, _fromAmount=1787491802285946880, _toAmount=1391114106804432909457, _trader=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe )
|
109 |
SmartToken.Approval( _owner=BancorNetwork, _spender=BancorConverter, _value=1391114106804432909457 )
|
110 |
SmartToken.Transfer( _from=BancorNetwork, _to=BancorConverter, _value=1391114106804432909457 )
|
111 |
Dai.Transfer( src=BancorConverter, dst=BancorNetwork, wad=237946450320045424661 )
|
112 |
BancorConverter.Conversion( _fromToken=SmartToken, _toToken=[Receiver] Dai, _trader=BancorNetwork, _amount=1391114106804432909457, _return=237946450320045424661, _conversionFee=476607692968013864 )
|
113 |
BancorConverter.PriceDataUpdate( _connectorToken=SmartToken, _tokenSupply=807216775726870627835250, _connectorBalance=416779561905307047746094, _connectorWeight=500000 )
|
114 |
BancorConverter.PriceDataUpdate( _connectorToken=[Receiver] Dai, _tokenSupply=807216775726870627835250, _connectorBalance=71193906034486269261632, _connectorWeight=500000 )
|
115 |
BancorNetwork.Conversion( _smartToken=SmartToken, _fromToken=SmartToken, _toToken=[Receiver] Dai, _fromAmount=1391114106804432909457, _toAmount=237946450320045424661, _trader=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe )
|
116 |
Dai.Transfer( src=BancorNetwork, dst=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe, wad=237946450320045424661 )
|
117 |
Dai.Transfer( src=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe, dst=0xd6EA703c547232B54FA83E62d7B0CD3086b1876C, wad=237946450320047075802 )
|
118 |
WETH9.Transfer( src=MatchingMarket, dst=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe, wad=1793250812571008183 )
|
119 |
MatchingMarket.LogItemUpdate( id=202171 )
|
120 |
MatchingMarket.LogTake( id=00000000000000000000000000000000000000000000000000000000000315BB, pair=CDD6659BCA20E2B28EA10EAD902280762AC8977C84459A152F90E561D50EDF8C, maker=0xd6EA703c547232B54FA83E62d7B0CD3086b1876C, pay_gem=WETH9, buy_gem=[Receiver] Dai, taker=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe, take_amt=1793250812571008183, give_amt=237946450320047075802, timestamp=1585202507 )
|
121 |
MatchingMarket.LogTrade( pay_amt=1793250812571008183, pay_gem=WETH9, buy_amt=237946450320047075802, buy_gem=[Receiver] Dai )
|
122 |
WETH9.Withdrawal( src=[Receiver] 0x8018280076d7fa2caa1147e441352e8a89e1ddbe, wad=1793250812571008183 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x1F573D6F...d79a7FF1C | |||||
0x337D2E56...8f7D6260B |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x37D077e5...c0c29230e |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x60A0e194...22cc313f3 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x6B175474...495271d0F | |||||
0x7270D32f...19409Ee29 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x77930FfA...f4e8D28F1 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x794e6e91...42133d08D | (OasisDEX) | ||||
0x79CFE786...33F2Cad38 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x7Bdc507B...13d910F93 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0x80182800...a89e1DDbe | 334.176582687742119996 Eth | 334.182341698027181299 Eth | 0.005759010285061303 | ||
0x9d6d492b...360FcaAa0
Miner
| (HTX Mining Pool) | 17.427098748330542318 Eth | 17.428955545437742318 Eth | 0.0018567971072 | |
0xC02aaA39...83C756Cc2 | 2,364,828.889587866400911845 Eth | 2,364,827.096337053829903662 Eth | 1.793250812571008183 | ||
0xc0829421...2db2cE315 | 11,178.797029426095088794 Eth | 11,180.584521228381035674 Eth | 1.78749180228594688 | ||
0xca348cf2...92f9cA7f1 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0xe047B527...aC166ffa2 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0xfC8d52ea...1851F402B |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0xfFa3739c...F1ef7Ff80 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 0
| |||
0xFFbFDb80...b429d11b5 |
19.850357548961785807 Eth
Nonce: 47208
|
19.848500751854585807 Eth
Nonce: 47209
| 0.0018567971072 |
Execution Trace
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.01030601( )
0x5b67ddb324c428bc13c36660707947ed4e168654.13abadab( )
-
SmartToken.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 415388447798502614836637 )
-
0x331543cc6b968a7265630892f3fa0acbea94614e.42289c40( )
-
MatchingMarket.getOffer( id=202171 ) => ( 443310000000000000000, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 58822803900000000000000, 0x6B175474E89094C44Da98b954EedeAC495271d0F )
-
MatchingMarket._dust( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 10000000000000000 )
-
0x5b67ddb324c428bc13c36660707947ed4e168654.eaeaeaaf( )
-
BancorConverter.CALL( )
ETH 1.78749180228594688
BancorNetwork.convert( _path=[0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315, 0xb1CD6e4153B2a390Cf00A6556b0fC1458C4A5533, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xE5Df055773Bf9710053923599504831c7DBdD697, 0x6B175474E89094C44Da98b954EedeAC495271d0F], _amount=1787491802285946880, _minReturn=1 ) => ( 237946450320045424661 )
-
ContractRegistry.addressOf( _contractName=436F6E7472616374466561747572657300000000000000000000000000000000 ) => ( 0x563172281800B139f69fB038cC2C08CaD56Ce699 )
-
SmartToken.CALL( )
-
ContractFeatures.isSupported( _contract=0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA, _features=1 ) => ( True )
-
BancorConverter.CALL( )
-
SmartToken.CALL( )
-
ContractFeatures.isSupported( _contract=0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146, _features=1 ) => ( True )
-
BancorConverter.CALL( )
-
ContractRegistry.addressOf( _contractName=42616E636F7247617350726963654C696D697400000000000000000000000000 ) => ( 0x607a5C47978e2Eb6d59C6C6f51bc0bF411f4b85a )
-
BancorGasPriceLimit.validateGasPrice( _gasPrice=5600860000 )
- ETH 1.78749180228594688
EtherToken.CALL( )
-
SmartToken.CALL( )
-
EtherToken.allowance( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD, 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 0 )
-
EtherToken.approve( _spender=0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA, _value=1787491802285946880 ) => ( success=True )
BancorConverter.change( _fromToken=0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315, _toToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _amount=1787491802285946880, _minReturn=1 ) => ( 1391114106804432909457 )
-
ContractRegistry.addressOf( _contractName=42616E636F724E6574776F726B00000000000000000000000000000000000000 ) => ( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD )
-
SmartToken.CALL( )
-
ContractRegistry.addressOf( _contractName=42616E636F72466F726D756C6100000000000000000000000000000000000000 ) => ( 0xE39B6ffff3F91630D9cCAC38550914653b34BC1C )
-
EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 11109343000903656295814 )
-
SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 8664549109729742015981315 )
-
BancorFormula.calculateCrossReserveReturn( _fromReserveBalance=11109343000903656295814, _fromReserveRatio=500000, _toReserveBalance=8664549109729742015981315, _toReserveRatio=500000, _amount=1787491802285946880 ) => ( 1393900513931782542760 )
-
SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 8664549109729742015981315 )
-
EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 11109343000903656295814 )
-
EtherToken.transferFrom( _from=0x3Ab6564d5c214bc416EE8421E05219960504eeAD, _to=0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA, _value=1787491802285946880 ) => ( success=True )
-
EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 11111130492705942242694 )
-
SmartToken.balanceOf( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD ) => ( 0 )
-
SmartToken.transfer( _to=0x3Ab6564d5c214bc416EE8421E05219960504eeAD, _value=1391114106804432909457 ) => ( success=True )
-
SmartToken.balanceOf( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD ) => ( 1391114106804432909457 )
-
SmartToken.CALL( )
-
EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 11111130492705942242694 )
-
SmartToken.CALL( )
-
SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 8663157995622937583071858 )
-
-
SmartToken.CALL( )
-
SmartToken.allowance( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD, 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 0 )
-
SmartToken.approve( _spender=0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146, _value=1391114106804432909457 ) => ( success=True )
BancorConverter.change( _fromToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _toToken=0x6B175474E89094C44Da98b954EedeAC495271d0F, _amount=1391114106804432909457, _minReturn=1 ) => ( 237946450320045424661 )
-
ContractRegistry.addressOf( _contractName=42616E636F724E6574776F726B00000000000000000000000000000000000000 ) => ( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD )
-
SmartToken.CALL( )
-
ContractRegistry.addressOf( _contractName=42616E636F72466F726D756C6100000000000000000000000000000000000000 ) => ( 0xE39B6ffff3F91630D9cCAC38550914653b34BC1C )
-
SmartToken.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 415388447798502614836637 )
-
Dai.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 71431852484806314686293 )
-
BancorFormula.calculateCrossReserveReturn( _fromReserveBalance=415388447798502614836637, _fromReserveRatio=500000, _toReserveBalance=71431852484806314686293, _toReserveRatio=500000, _amount=1391114106804432909457 ) => ( 238423058013013438525 )
-
Dai.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 71431852484806314686293 )
-
SmartToken.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 415388447798502614836637 )
-
SmartToken.transferFrom( _from=0x3Ab6564d5c214bc416EE8421E05219960504eeAD, _to=0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146, _value=1391114106804432909457 ) => ( success=True )
-
SmartToken.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 416779561905307047746094 )
-
Dai.balanceOf( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD ) => ( 0 )
-
Dai.transfer( dst=0x3Ab6564d5c214bc416EE8421E05219960504eeAD, wad=237946450320045424661 ) => ( True )
-
Dai.balanceOf( 0x3Ab6564d5c214bc416EE8421E05219960504eeAD ) => ( 237946450320045424661 )
-
SmartToken.CALL( )
-
SmartToken.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 416779561905307047746094 )
-
SmartToken.CALL( )
-
Dai.balanceOf( 0xd99b0EFeeA095b87C5aD8BCc8B955eD5Ca5Ba146 ) => ( 71193906034486269261632 )
-
-
Dai.balanceOf( 0x8018280076d7fA2cAa1147e441352E8a89e1DDbe ) => ( 1651231 )
-
Dai.transfer( dst=0x8018280076d7fA2cAa1147e441352E8a89e1DDbe, wad=237946450320045424661 ) => ( True )
-
Dai.balanceOf( 0x8018280076d7fA2cAa1147e441352E8a89e1DDbe ) => ( 237946450320047075892 )
-
-
0x331543cc6b968a7265630892f3fa0acbea94614e.b1058cfd( )
-
Dai.balanceOf( 0x8018280076d7fA2cAa1147e441352E8a89e1DDbe ) => ( 237946450320047075892 )
-
MatchingMarket.getOffer( id=202171 ) => ( 443310000000000000000, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 58822803900000000000000, 0x6B175474E89094C44Da98b954EedeAC495271d0F )
-
Dai.allowance( 0x8018280076d7fA2cAa1147e441352E8a89e1DDbe, 0x794e6e91555438aFc3ccF1c5076A74F42133d08D ) => ( 115792089237316195423570985008687907853269984665640564039457584007913129639935 )
MatchingMarket.buy( id=202171, amount=1793250812571008183 ) => ( True )
-
Dai.transferFrom( src=0x8018280076d7fA2cAa1147e441352E8a89e1DDbe, dst=0xd6EA703c547232B54FA83E62d7B0CD3086b1876C, wad=237946450320047075802 ) => ( True )
-
WETH9.transfer( dst=0x8018280076d7fA2cAa1147e441352E8a89e1DDbe, wad=1793250812571008183 ) => ( True )
-
-
WETH9.balanceOf( 0x8018280076d7fA2cAa1147e441352E8a89e1DDbe ) => ( 1793250812571008184 )
WETH9.withdraw( wad=1793250812571008183 )
- ETH 1.793250812571008183
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.CALL( )
- ETH 1.793250812571008183
-
0x7270d32fab6a690d80aff3ae3f45d7a19409ee29.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0xfc8d52ea6f1a991bfd7358916a4b5c81851f402b.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0x337d2e56cf5f9c93bade8af043d65af8f7d6260b.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0x79cfe78601ea05327a330d80428abd433f2cad38.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0x60a0e194f86a69d13d01579b052c4fb22cc313f3.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0x77930ffae79a5d1f2be1f868ac4b669f4e8d28f1.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0x37d077e5c75ea937299c66cb5b4b3e4c0c29230e.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0x7bdc507b4965414545e12ecf242018e13d910f93.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0xe047b527bbd567bca10bdfdd1aacb9dac166ffa2.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0xca348cf2833850d010c383c6fdd32d192f9ca7f1.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
0xffa3739cb586c3d882654d79827f23af1ef7ff80.CALL( )
-
0x8018280076d7fa2caa1147e441352e8a89e1ddbe.SELFDESTRUCT( )
-
File 1 of 14: EtherToken
File 2 of 14: BancorNetwork
File 3 of 14: BancorConverter
File 4 of 14: SmartToken
File 5 of 14: BancorConverter
File 6 of 14: Dai
File 7 of 14: MatchingMarket
File 8 of 14: WETH9
File 9 of 14: ContractRegistry
File 10 of 14: SmartToken
File 11 of 14: ContractFeatures
File 12 of 14: SmartToken
File 13 of 14: BancorGasPriceLimit
File 14 of 14: 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; } } /* 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 2 of 14: BancorNetwork
// File: contracts/token/interfaces/IERC20Token.sol pragma solidity 0.4.26; /* 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) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} 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); } // File: contracts/IBancorNetwork.sol pragma solidity 0.4.26; /* Bancor Network interface */ contract IBancorNetwork { function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertForPrioritized4( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); // deprecated, backward compatibility function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256); // deprecated, backward compatibility function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public returns (uint256); // deprecated, backward compatibility function convertForPrioritized3( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); } // File: contracts/FeatureIds.sol pragma solidity 0.4.26; /** * @dev Id definitions for bancor contract features * * Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } // File: contracts/utility/interfaces/IWhitelist.sol pragma solidity 0.4.26; /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } // File: contracts/converter/interfaces/IBancorConverter.sol pragma solidity 0.4.26; /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256); function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256); function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {this;} function conversionFee() public view returns (uint32) {this;} function reserves(address _address) public view returns (uint256, uint32, bool, bool, bool) {_address; this;} function getReserveBalance(IERC20Token _reserveToken) public view returns (uint256); function reserveTokens(uint256 _index) public view returns (IERC20Token) {_index; this;} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool); function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256); function connectorTokens(uint256 _index) public view returns (IERC20Token); function connectorTokenCount() public view returns (uint16); } // File: contracts/converter/interfaces/IBancorFormula.sol pragma solidity 0.4.26; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); // deprecated, backward compatibility function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: contracts/converter/interfaces/IBancorGasPriceLimit.sol pragma solidity 0.4.26; /* Bancor Gas Price Limit interface */ contract IBancorGasPriceLimit { function gasPrice() public view returns (uint256) {this;} function validateGasPrice(uint256) public view; } // File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* 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) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(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); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() 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)); _; } } // File: contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.4.26; /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/token/interfaces/INonStandardERC20.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve */ contract INonStandardERC20 { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public; } // File: contracts/utility/TokenHolder.sol pragma solidity 0.4.26; /** * @dev 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. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, Owned, Utils { /** * @dev initializes a new TokenHolder instance */ constructor() 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) { INonStandardERC20(_token).transfer(_to, _amount); } } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.4.26; /* Contract Registry interface */ contract IContractRegistry { function addressOf(bytes32 _contractName) public view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address); } // File: contracts/utility/ContractRegistryClient.sol pragma solidity 0.4.26; /** * @dev Base contract for ContractRegistry clients */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures"; bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit"; bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory"; bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public adminOnly; // only an administrator can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { require(msg.sender == addressOf(_contractName)); _; } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(_registry) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(!adminOnly || isAdmin()); // get the new contract-registry address newRegistry = addressOf(CONTRACT_REGISTRY); // verify that the new contract-registry is different and not zero require(newRegistry != address(registry) && newRegistry != address(0)); // verify that the new contract-registry is pointing to a non-zero contract-registry require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0)); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = IContractRegistry(newRegistry); } /** * @dev restores the previous contract-registry */ function restoreRegistry() public { // verify that this function is permitted require(isAdmin()); // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _adminOnly indicates whether or not permission is restricted to administrator only */ function restrictRegistryUpdate(bool _adminOnly) public { // verify that this function is permitted require(adminOnly != _adminOnly && isAdmin()); // change the permission to update the contract-registry adminOnly = _adminOnly; } /** * @dev returns whether or not the caller is an administrator */ function isAdmin() internal view returns (bool) { return msg.sender == owner; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: contracts/utility/interfaces/IContractFeatures.sol pragma solidity 0.4.26; /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } // File: contracts/utility/interfaces/IAddressList.sol pragma solidity 0.4.26; /* Address list interface */ contract IAddressList { mapping (address => bool) public listedAddresses; } // File: contracts/token/interfaces/IEtherToken.sol pragma solidity 0.4.26; /* Ether Token interface */ contract IEtherToken is ITokenHolder, IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function withdrawTo(address _to, uint256 _amount) public; } // File: contracts/token/interfaces/ISmartToken.sol pragma solidity 0.4.26; /* 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; } // File: contracts/bancorx/interfaces/IBancorX.sol pragma solidity 0.4.26; contract IBancorX { function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public; function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256); } // File: contracts/BancorNetwork.sol pragma solidity 0.4.26; /** * @dev The BancorNetwork contract is the main entry point for Bancor token conversions. * It also allows for the conversion of any token in the Bancor Network to any other token in a single transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token to another token in the Bancor Network, * when the conversion cannot necessarily be done by a 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; 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 as opposed to smart token addresses). * * Format: * [source token, smart token, to token, smart token, to token...] */ contract BancorNetwork is IBancorNetwork, TokenHolder, ContractRegistryClient, FeatureIds { using SafeMath for uint256; uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000; uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000; uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee address public signerAddress = 0x0; // verified address that allows conversions with higher gas price mapping (address => bool) public etherTokens; // list of all supported ether tokens mapping (bytes32 => bool) public conversionHashes; // list of conversion hashes, to prevent re-use of the same hash /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken smart token governed by the converter * @param _fromToken ERC20 token converted from * @param _toToken ERC20 token converted to * @param _fromAmount amount converted, in fromToken * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( address indexed _smartToken, address indexed _fromToken, address indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new BancorNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to update the signer address * * @param _signerAddress new signer address */ function setSignerAddress(address _signerAddress) public ownerOnly validAddress(_signerAddress) notThis(_signerAddress) { signerAddress = _signerAddress; } /** * @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 verifies that the signer address is the one associated with the public key from a given elliptic curve signature * note that the signature is valid only for one conversion, and that it expires after the give block */ function verifyTrustedSender(IERC20Token[] _path, address _addr, uint256[] memory _signature) private { uint256 blockNumber = _signature[1]; // check that the current block number doesn't exceeded the maximum allowed with the current signature require(block.number <= blockNumber); // create the hash of the given signature bytes32 hash = keccak256(abi.encodePacked(blockNumber, tx.gasprice, _addr, msg.sender, _signature[0], _path)); // check that it is the first conversion with the given signature require(!conversionHashes[hash]); // verify that the signing address is identical to the trusted signer address in the contract bytes32 prefixedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); require(ecrecover(prefixedHash, uint8(_signature[2]), bytes32(_signature[3]), bytes32(_signature[4])) == signerAddress); // mark the hash so that it can't be used multiple times conversionHashes[hash] = true; } /** * @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 network 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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function convertFor2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) { return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee); } /** * @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. * this version of the function also allows the verified signer * to bypass the universal gas price limit. * note that the network 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 * @param _signature an array of the following elements: * [0] uint256 custom value that was signed for prioritized conversion * [1] uint256 if the current block exceeded the given parameter - it is cancelled * [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit * [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit * [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function convertForPrioritized4( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { // verify that the conversion parameters are legal verifyConversionParams(_path, _for, _for, _signature); // handle msg.value handleValue(_path[0], _amount, false); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, _affiliateAccount, _affiliateFee); // 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 IERC20Token toToken = _path[_path.length - 1]; if (etherTokens[toToken]) IEtherToken(toToken).withdrawTo(_for, amount); else ensureTransferFrom(toToken, this, _for, amount); return amount; } /** * @dev converts any other token to BNT in the bancor network * by following a predefined conversion path and transfers the resulting * tokens to BancorX. * note that the network should already have been given allowance of the source token (if not ETH) * * @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 _toBlockchain blockchain BNT will be issued on * @param _to address/account on _toBlockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return xConvertPrioritized3(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee); } /** * @dev converts any other token to BNT in the bancor network * by following a predefined conversion path and transfers the resulting * tokens to BancorX. * this version of the function also allows the verified signer * to bypass the universal gas price limit. * note that the network should already have been given allowance of the source token (if not ETH) * * @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 _toBlockchain blockchain BNT will be issued on * @param _to address/account on _toBlockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _signature an array of the following elements: * [0] uint256 custom value that was signed for prioritized conversion; must be equal to _amount * [1] uint256 if the current block exceeded the given parameter - it is cancelled * [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit * [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit * [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvertPrioritized3( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { // verify that the custom value (if valid) is equal to _amount require(_signature.length == 0 || _signature[0] == _amount); // verify that the conversion parameters are legal verifyConversionParams(_path, msg.sender, this, _signature); // verify that the destination token is BNT require(_path[_path.length - 1] == addressOf(BNT_TOKEN)); // handle msg.value handleValue(_path[0], _amount, true); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, _affiliateAccount, _affiliateFee); // transfer the resulting amount to BancorX IBancorX(addressOf(BANCOR_X)).xTransfer(_toBlockchain, _to, amount, _conversionId); return amount; } /** * @dev executes the actual conversion by following the conversion path * * @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 _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens issued */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; uint256 lastIndex = _path.length - 1; address bntToken; if (address(_affiliateAccount) == 0) { require(_affiliateFee == 0); bntToken = address(0); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee); bntToken = addressOf(BNT_TOKEN); } // iterate over the conversion path for (uint256 i = 2; i <= lastIndex; i += 2) { IBancorConverter converter = IBancorConverter(ISmartToken(_path[i - 1]).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 (_path[i - 1] != _path[i - 2]) ensureAllowance(_path[i - 2], converter, fromAmount); // make the conversion - if it's the last one, also provide the minimum return value toAmount = converter.change(_path[i - 2], _path[i], fromAmount, i == lastIndex ? _minReturn : 1); // pay affiliate-fee if needed if (address(_path[i]) == bntToken) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(_path[i].transfer(_affiliateAccount, affiliateAmount)); toAmount -= affiliateAmount; bntToken = address(0); } emit Conversion(_path[i - 1], _path[i - 2], _path[i], fromAmount, toAmount, msg.sender); fromAmount = toAmount; } return toAmount; } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(uint256(keccak256("getReturn(address,address,uint256)") >> (256 - 4 * 8))); function getReturn(address _dest, address _fromToken, address _toToken, uint256 _amount) internal view returns (uint256, uint256) { uint256[2] memory ret; bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _fromToken, _toToken, _amount); assembly { let success := staticcall( gas, // gas remaining _dest, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 64 // output length ) if iszero(success) { revert(0, 0) } } return (ret[0], ret[1]); } /** * @dev calculates the expected return of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the user * * @return amount of _path[_path.length - 1] tokens that the user will receive * @return amount of _path[_path.length - 1] tokens that the user will pay as fee */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 ratio; IBancorConverter converter; IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token fromToken = _path[i - 2]; IERC20Token smartToken = _path[i - 1]; IERC20Token toToken = _path[i]; if (toToken == smartToken) { // buy the smart token // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { supply = smartToken.totalSupply(); converter = IBancorConverter(ISmartToken(smartToken).owner()); } // calculate the amount & the conversion fee balance = converter.getConnectorBalance(fromToken); (, ratio, , , ) = converter.connectors(fromToken); amount = formula.calculatePurchaseReturn(supply, balance, ratio, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply += amount; } else if (fromToken == smartToken) { // sell the smart token // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { supply = smartToken.totalSupply(); converter = IBancorConverter(ISmartToken(smartToken).owner()); } // calculate the amount & the conversion fee balance = converter.getConnectorBalance(toToken); (, ratio, , , ) = converter.connectors(toToken); amount = formula.calculateSaleReturn(supply, balance, ratio, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply -= amount; } else { // cross reserve conversion // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { converter = IBancorConverter(ISmartToken(smartToken).owner()); } (amount, fee) = getReturn(converter, fromToken, toToken, amount); } } return (amount, fee); } /** * @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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function claimAndConvertFor2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) { // we need to transfer the tokens from the caller to the network 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]; ensureTransferFrom(fromToken, msg.sender, this, _amount); return convertFor2(_path, _amount, _minReturn, _for, _affiliateAccount, _affiliateFee); } /** * @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 network 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 _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function convert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) { return convertFor2(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee); } /** * @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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function claimAndConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) { return claimAndConvertFor2(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee); } /** * @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return * true on success but revert on failure instead * * @param _token the token to transfer * @param _from the address to transfer the tokens from * @param _to the address to transfer the tokens to * @param _amount the amount to transfer */ function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private { // We must assume that functions `transfer` and `transferFrom` do not return anything, // because not all tokens abide the requirement of the ERC20 standard to return success or failure. // This is because in the current compiler version, the calling contract can handle more returned data than expected but not less. // This may change in the future, so that the calling contract will revert if the size of the data is not exactly what it expects. uint256 prevBalance = _token.balanceOf(_to); if (_from == address(this)) INonStandardERC20(_token).transfer(_to, _amount); else INonStandardERC20(_token).transferFrom(_from, _to, _amount); uint256 postBalance = _token.balanceOf(_to); require(postBalance > prevBalance); } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @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 { uint256 allowance = _token.allowance(this, _spender); if (allowance < _value) { if (allowance > 0) INonStandardERC20(_token).approve(_spender, 0); INonStandardERC20(_token).approve(_spender, _value); } } function getSignature( uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (uint256[] memory) { if (_v == 0x0 && _r == 0x0 && _s == 0x0) return new uint256[](0); uint256[] memory signature = new uint256[](5); signature[0] = _customVal; signature[1] = _block; signature[2] = uint256(_v); signature[3] = uint256(_r); signature[4] = uint256(_s); return signature; } function verifyConversionParams( IERC20Token[] _path, address _sender, address _receiver, uint256[] memory _signature ) private { // verify that the number of elements is odd and that maximum number of 'hops' is 10 require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); // verify that the account which should receive the conversion result is whitelisted IContractFeatures features = IContractFeatures(addressOf(CONTRACT_FEATURES)); for (uint256 i = 1; i < _path.length; i += 2) { IBancorConverter converter = IBancorConverter(ISmartToken(_path[i]).owner()); if (features.isSupported(converter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) { IWhitelist whitelist = converter.conversionWhitelist(); require(whitelist == address(0) || whitelist.isWhitelisted(_receiver)); } } if (_signature.length >= 5) { // verify signature verifyTrustedSender(_path, _sender, _signature); } else { // verify gas price limit IBancorGasPriceLimit gasPriceLimit = IBancorGasPriceLimit(addressOf(BANCOR_GAS_PRICE_LIMIT)); gasPriceLimit.validateGasPrice(tx.gasprice); } } function handleValue(IERC20Token _token, uint256 _amount, bool _claim) private { // if ETH is provided, ensure that the amount is identical to _amount, verify that the source token is an ether token and deposit the ETH in it if (msg.value > 0) { require(_amount == msg.value && etherTokens[_token]); IEtherToken(_token).deposit.value(msg.value)(); } // Otherwise, claim the tokens from the sender if needed else if (_claim) { ensureTransferFrom(_token, msg.sender, this, _amount); } } /** * @dev deprecated, backward compatibility */ function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256) { return convert2(_path, _amount, _minReturn, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256) { return claimAndConvert2(_path, _amount, _minReturn, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public payable returns (uint256) { return convertFor2(_path, _amount, _minReturn, _for, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public returns (uint256) { return claimAndConvertFor2(_path, _amount, _minReturn, _for, address(0), 0); } /** * @dev deprecated, backward compatibility */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, address(0), 0); } /** * @dev deprecated, backward compatibility */ function xConvertPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId, uint256[] memory _signature ) public payable returns (uint256) { return xConvertPrioritized3(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, _signature, address(0), 0); } /** * @dev deprecated, backward compatibility */ function xConvertPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256) { // workaround the 'stack too deep' compilation error uint256[] memory signature = getSignature(_amount, _block, _v, _r, _s); return xConvertPrioritized3(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, signature, address(0), 0); // return xConvertPrioritized3(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(_amount, _block, _v, _r, _s), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertForPrioritized3( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256) { return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_customVal, _block, _v, _r, _s), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertForPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256) { return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_amount, _block, _v, _r, _s), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { _nonce; return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_amount, _block, _v, _r, _s), address(0), 0); } }
File 3 of 14: BancorConverter
// File: contracts/token/interfaces/IERC20Token.sol pragma solidity 0.4.26; /* 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) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} 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); } // File: contracts/utility/interfaces/IWhitelist.sol pragma solidity 0.4.26; /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } // File: contracts/converter/interfaces/IBancorConverter.sol pragma solidity 0.4.26; /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256); function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256); function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256); function conversionsEnabled() public view returns (bool) {this;} function conversionWhitelist() public view returns (IWhitelist) {this;} function conversionFee() public view returns (uint32) {this;} function reserves(address _address) public view returns (uint256, uint32, bool, bool, bool) {_address; this;} function getReserveBalance(IERC20Token _reserveToken) public view returns (uint256); function reserveTokens(uint256 _index) public view returns (IERC20Token) {_index; this;} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool); function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256); function connectorTokens(uint256 _index) public view returns (IERC20Token); function connectorTokenCount() public view returns (uint16); } // File: contracts/converter/interfaces/IBancorConverterUpgrader.sol pragma solidity 0.4.26; /* Bancor Converter Upgrader interface */ contract IBancorConverterUpgrader { function upgrade(bytes32 _version) public; function upgrade(uint16 _version) public; } // File: contracts/converter/interfaces/IBancorFormula.sol pragma solidity 0.4.26; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); // deprecated, backward compatibility function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: contracts/IBancorNetwork.sol pragma solidity 0.4.26; /* Bancor Network interface */ contract IBancorNetwork { function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertForPrioritized4( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); // deprecated, backward compatibility function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256); // deprecated, backward compatibility function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public returns (uint256); // deprecated, backward compatibility function convertForPrioritized3( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); } // File: contracts/FeatureIds.sol pragma solidity 0.4.26; /** * @dev Id definitions for bancor contract features * * Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } // File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* 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) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(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); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Managed.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract management * Note that a managed contract must also have an owner */ contract Managed is Owned { address public manager; address public newManager; /** * @dev triggered when the manager is updated * * @param _prevManager previous manager * @param _newManager new manager */ event ManagerUpdate(address indexed _prevManager, address indexed _newManager); /** * @dev initializes a new Managed instance */ constructor() public { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } // allows execution by either the owner or the manager only modifier ownerOrManagerOnly { require(msg.sender == owner || 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 ownerOrManagerOnly { require(_newManager != manager); newManager = _newManager; } /** * @dev used by a new manager to accept a management transfer */ function acceptManagement() public { require(msg.sender == newManager); emit ManagerUpdate(manager, newManager); manager = newManager; newManager = address(0); } } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() 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)); _; } } // File: contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.4.26; /* Contract Registry interface */ contract IContractRegistry { function addressOf(bytes32 _contractName) public view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address); } // File: contracts/utility/ContractRegistryClient.sol pragma solidity 0.4.26; /** * @dev Base contract for ContractRegistry clients */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures"; bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit"; bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory"; bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public adminOnly; // only an administrator can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { require(msg.sender == addressOf(_contractName)); _; } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(_registry) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(!adminOnly || isAdmin()); // get the new contract-registry address newRegistry = addressOf(CONTRACT_REGISTRY); // verify that the new contract-registry is different and not zero require(newRegistry != address(registry) && newRegistry != address(0)); // verify that the new contract-registry is pointing to a non-zero contract-registry require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0)); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = IContractRegistry(newRegistry); } /** * @dev restores the previous contract-registry */ function restoreRegistry() public { // verify that this function is permitted require(isAdmin()); // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _adminOnly indicates whether or not permission is restricted to administrator only */ function restrictRegistryUpdate(bool _adminOnly) public { // verify that this function is permitted require(adminOnly != _adminOnly && isAdmin()); // change the permission to update the contract-registry adminOnly = _adminOnly; } /** * @dev returns whether or not the caller is an administrator */ function isAdmin() internal view returns (bool) { return msg.sender == owner; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: contracts/utility/interfaces/IContractFeatures.sol pragma solidity 0.4.26; /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } // File: contracts/utility/interfaces/IAddressList.sol pragma solidity 0.4.26; /* Address list interface */ contract IAddressList { mapping (address => bool) public listedAddresses; } // File: contracts/token/interfaces/ISmartToken.sol pragma solidity 0.4.26; /* 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; } // File: contracts/token/interfaces/ISmartTokenController.sol pragma solidity 0.4.26; /* Smart Token Controller interface */ contract ISmartTokenController { function claimTokens(address _from, uint256 _amount) public; function token() public view returns (ISmartToken) {this;} } // File: contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.4.26; /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/token/interfaces/INonStandardERC20.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve */ contract INonStandardERC20 { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public; } // File: contracts/utility/TokenHolder.sol pragma solidity 0.4.26; /** * @dev 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. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, Owned, Utils { /** * @dev initializes a new TokenHolder instance */ constructor() 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) { INonStandardERC20(_token).transfer(_to, _amount); } } // File: contracts/token/SmartTokenController.sol pragma solidity 0.4.26; /** * @dev 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 ISmartTokenController, TokenHolder { ISmartToken public token; // Smart Token contract address public bancorX; // BancorX contract /** * @dev initializes a new SmartTokenController instance * * @param _token smart token governed by the controller */ constructor(ISmartToken _token) public validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { require(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { require(token.owner() != address(this)); _; } /** * @dev allows transferring the token ownership * the new owner needs 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 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); } /** * @dev allows the associated BancorX contract to claim tokens from any address (so that users * dont have to first give allowance when calling BancorX) * * @param _from address to claim the tokens from * @param _amount the amount of tokens to claim */ function claimTokens(address _from, uint256 _amount) public { // only the associated BancorX contract may call this method require(msg.sender == bancorX); // destroy the tokens belonging to _from, and issue the same amount to bancorX token.destroy(_from, _amount); token.issue(msg.sender, _amount); } /** * @dev allows the owner to set the associated BancorX contract * @param _bancorX BancorX contract */ function setBancorX(address _bancorX) public ownerOnly { bancorX = _bancorX; } } // File: contracts/token/interfaces/IEtherToken.sol pragma solidity 0.4.26; /* Ether Token interface */ contract IEtherToken is ITokenHolder, IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function withdrawTo(address _to, uint256 _amount) public; } // File: contracts/bancorx/interfaces/IBancorX.sol pragma solidity 0.4.26; contract IBancorX { function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public; function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256); } // File: contracts/converter/BancorConverter.sol pragma solidity 0.4.26; /** * @dev Bancor Converter * * The Bancor converter allows for conversions between a Smart Token and other ERC20 tokens and between different ERC20 tokens and themselves. * * The ERC20 reserve balance can be virtual, meaning that conversions between reserve tokens are based on the virtual balance instead of relying on the actual reserve balance. * * This mechanism opens the possibility to create different financial tools (for example, lower slippage in conversions). * * The converter is upgradable (just like any SmartTokenController) and all upgrades are opt-in. * * 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 * - gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer * * Other potential solutions might include a commit/reveal based schemes * - Possibly add getters for the reserve fields so that the client won't need to rely on the order in the struct */ contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractRegistryClient, FeatureIds { using SafeMath for uint256; uint32 private constant RATIO_RESOLUTION = 1000000; uint64 private constant CONVERSION_FEE_RESOLUTION = 1000000; struct Reserve { uint256 virtualBalance; // reserve virtual balance uint32 ratio; // reserve ratio, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isSaleEnabled; // is sale of the reserve token enabled, can be set by the owner bool isSet; // used to tell if the mapping element is defined } /** * @dev version number */ uint16 public version = 23; string public converterType = 'bancor'; IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public reserveTokens; // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead) mapping (address => Reserve) public reserves; // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead) uint32 private totalReserveRatio = 0; // used to efficiently prevent increasing the total reserve ratio 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 /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken ERC20 token converted from * @param _toToken ERC20 token converted to * @param _trader wallet that initiated the trade * @param _amount amount converted, in fromToken * @param _return amount returned, minus conversion fee * @param _conversionFee conversion fee */ event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered after a conversion with new price data * * @param _connectorToken reserve token * @param _tokenSupply smart token supply * @param _connectorBalance reserve balance * @param _connectorWeight reserve ratio */ event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** * @dev triggered when conversions are enabled/disabled * * @param _conversionsEnabled true if conversions are enabled, false if not */ event ConversionsEnable(bool _conversionsEnabled); /** * @dev triggered when virtual balances are enabled/disabled * * @param _enabled true if virtual balances are enabled, false if not */ event VirtualBalancesEnable(bool _enabled); /** * @dev initializes a new BancorConverter instance * * @param _token smart token governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm * @param _reserveToken optional, initial reserve, allows defining the first reserve at deployment time * @param _reserveRatio optional, ratio for the initial reserve */ constructor( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _reserveToken, uint32 _reserveRatio ) ContractRegistryClient(_registry) public SmartTokenController(_token) validConversionFee(_maxConversionFee) { IContractFeatures features = IContractFeatures(addressOf(CONTRACT_FEATURES)); // initialize supported features if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_reserveToken != address(0)) addReserve(_reserveToken, _reserveRatio); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(IERC20Token _address) { require(reserves[_address].isSet); _; } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= CONVERSION_FEE_RESOLUTION); _; } // validates reserve ratio modifier validReserveRatio(uint32 _ratio) { require(_ratio > 0 && _ratio <= RATIO_RESOLUTION); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { require(conversionsEnabled); _; } // allows execution only if the total-supply of the token is greater than zero modifier totalSupplyGreaterThanZeroOnly { require(token.totalSupply() > 0); _; } // allows execution only on a multiple-reserve converter modifier multipleReservesOnly { require(reserveTokens.length > 1); _; } /** * @dev returns the number of reserve tokens defined * note that prior to version 17, you should use 'connectorTokenCount' instead * * @return number of reserve tokens */ function reserveTokenCount() public view returns (uint16) { return uint16(reserveTokens.length); } /** * @dev allows the owner to update & enable the conversion whitelist contract address * when set, only addresses that are whitelisted are actually allowed to use the converter * note that the whitelist check is actually done by the BancorNetwork contract * * @param _whitelist address of a whitelist contract */ function setConversionWhitelist(IWhitelist _whitelist) public ownerOnly notThis(_whitelist) { conversionWhitelist = _whitelist; } /** * @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 { if (conversionsEnabled == _disable) { conversionsEnabled = !_disable; emit ConversionsEnable(conversionsEnabled); } } /** * @dev allows transferring the token ownership * the new owner needs to accept the transfer * can only be called by the contract owner * note that token ownership can only be transferred while the owner is the converter upgrader contract * * @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly only(BANCOR_CONVERTER_UPGRADER) { super.transferTokenOwnership(_newOwner); } /** * @dev used by a new owner to accept a token ownership transfer * can only be called by the contract owner * note that token ownership can only be accepted if its total-supply is greater than zero */ function acceptTokenOwnership() public ownerOnly totalSupplyGreaterThanZeroOnly { super.acceptTokenOwnership(); } /** * @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 { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); emit ConversionFeeUpdate(conversionFee, _conversionFee); conversionFee = _conversionFee; } /** * @dev given a return amount, returns the amount minus the conversion fee * * @param _amount return amount * @param _magnitude 1 for standard conversion, 2 for cross reserve conversion * * @return return amount minus conversion fee */ function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) { return _amount.mul((CONVERSION_FEE_RESOLUTION - conversionFee) ** _magnitude).div(CONVERSION_FEE_RESOLUTION ** _magnitude); } /** * @dev withdraws tokens held by the converter and sends them to an account * can only be called by the owner * note that reserve tokens can only be withdrawn by the owner while the converter is inactive * unless the owner is the converter upgrader contract * * @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 { address converterUpgrader = addressOf(BANCOR_CONVERTER_UPGRADER); // if the token is not a reserve token, allow withdrawal // otherwise verify that the converter is inactive or that the owner is the upgrader contract require(!reserves[_token].isSet || token.owner() != address(this) || owner == converterUpgrader); super.withdrawTokens(_token, _to, _amount); } /** * @dev upgrades the converter to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership/acceptManagement on the new converter after the upgrade */ function upgrade() public ownerOnly { IBancorConverterUpgrader converterUpgrader = IBancorConverterUpgrader(addressOf(BANCOR_CONVERTER_UPGRADER)); transferOwnership(converterUpgrader); converterUpgrader.upgrade(version); acceptOwnership(); } /** * @dev defines a new reserve for the token * can only be called by the owner while the converter is inactive * note that prior to version 17, you should use 'addConnector' instead * * @param _token address of the reserve token * @param _ratio constant reserve ratio, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _ratio) public ownerOnly inactive validAddress(_token) notThis(_token) validReserveRatio(_ratio) { require(_token != token && !reserves[_token].isSet && totalReserveRatio + _ratio <= RATIO_RESOLUTION); // validate input reserves[_token].ratio = _ratio; reserves[_token].isVirtualBalanceEnabled = false; reserves[_token].virtualBalance = 0; reserves[_token].isSaleEnabled = true; reserves[_token].isSet = true; reserveTokens.push(_token); totalReserveRatio += _ratio; } /** * @dev updates a reserve's virtual balance * only used during an upgrade process * can only be called by the contract owner while the owner is the converter upgrader contract * note that prior to version 17, you should use 'updateConnector' instead * * @param _reserveToken address of the reserve token * @param _virtualBalance new reserve virtual balance, or 0 to disable virtual balance */ function updateReserveVirtualBalance(IERC20Token _reserveToken, uint256 _virtualBalance) public ownerOnly only(BANCOR_CONVERTER_UPGRADER) validReserve(_reserveToken) { Reserve storage reserve = reserves[_reserveToken]; reserve.isVirtualBalanceEnabled = _virtualBalance != 0; reserve.virtualBalance = _virtualBalance; } /** * @dev enables virtual balance for the reserves * virtual balance only affects conversions between reserve tokens * virtual balance of all reserves can only scale by the same factor, to keep the ratio between them the same * note that the balance is determined during the execution of this function and set statically - * meaning that it's not calculated dynamically based on the factor after each conversion * can only be called by the contract owner while the converter is active * * @param _scaleFactor percentage, 100-1000 (100 = no virtual balance, 1000 = virtual balance = actual balance * 10) */ function enableVirtualBalances(uint16 _scaleFactor) public ownerOnly active { // validate input require(_scaleFactor >= 100 && _scaleFactor <= 1000); bool enable = _scaleFactor != 100; // iterate through the reserves and scale their balance by the ratio provided, // or disable virtual balance altogether if a factor of 100% is passed in IERC20Token reserveToken; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; Reserve storage reserve = reserves[reserveToken]; reserve.isVirtualBalanceEnabled = enable; reserve.virtualBalance = enable ? reserveToken.balanceOf(this).mul(_scaleFactor).div(100) : 0; } emit VirtualBalancesEnable(enable); } /** * @dev disables converting from the given reserve token in case the reserve token got compromised * can only be called by the owner * note that converting to the token is still enabled regardless of this flag and it cannot be disabled by the owner * note that prior to version 17, you should use 'disableConnectorSale' instead * * @param _reserveToken reserve token contract address * @param _disable true to disable the token, false to re-enable it */ function disableReserveSale(IERC20Token _reserveToken, bool _disable) public ownerOnly validReserve(_reserveToken) { reserves[_reserveToken].isSaleEnabled = !_disable; } /** * @dev returns the reserve's ratio * added in version 22 * * @param _reserveToken reserve token contract address * * @return reserve ratio */ function getReserveRatio(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return reserves[_reserveToken].ratio; } /** * @dev returns the reserve's virtual balance if one is defined, otherwise returns the actual balance * note that prior to version 17, you should use 'getConnectorBalance' instead * * @param _reserveToken reserve token contract address * * @return reserve balance */ function getReserveBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { Reserve storage reserve = reserves[_reserveToken]; return reserve.isVirtualBalanceEnabled ? reserve.virtualBalance : _reserveToken.balanceOf(this); } /** * @dev calculates the expected return of converting a given amount of tokens * * @param _fromToken contract address of the token to convert from * @param _toToken contract address of the token to convert to * @param _amount amount of tokens received from the user * * @return amount of tokens that the user will receive * @return amount of tokens that the user will pay as fee */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its reserves if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // conversion between 2 reserves return getCrossReserveReturn(_fromToken, _toToken, _amount); } /** * @dev calculates the expected return of buying with a given amount of tokens * * @param _reserveToken contract address of the reserve token * @param _depositAmount amount of reserve-tokens received from the user * * @return amount of supply-tokens that the user will receive * @return amount of supply-tokens that the user will pay as fee */ function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount) public view active validReserve(_reserveToken) returns (uint256, uint256) { Reserve storage reserve = reserves[_reserveToken]; require(reserve.isSaleEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = _reserveToken.balanceOf(this); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount); uint256 finalAmount = getFinalAmount(amount, 1); // return the amount minus the conversion fee and the conversion fee return (finalAmount, amount - finalAmount); } /** * @dev calculates the expected return of selling a given amount of tokens * * @param _reserveToken contract address of the reserve token * @param _sellAmount amount of supply-tokens received from the user * * @return amount of reserve-tokens that the user will receive * @return amount of reserve-tokens that the user will pay as fee */ function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount) public view active validReserve(_reserveToken) returns (uint256, uint256) { Reserve storage reserve = reserves[_reserveToken]; uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = _reserveToken.balanceOf(this); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.calculateSaleReturn(tokenSupply, reserveBalance, reserve.ratio, _sellAmount); uint256 finalAmount = getFinalAmount(amount, 1); // return the amount minus the conversion fee and the conversion fee return (finalAmount, amount - finalAmount); } /** * @dev calculates the expected return of converting a given amount from one reserve to another * note that prior to version 17, you should use 'getCrossConnectorReturn' instead * * @param _fromReserveToken contract address of the reserve token to convert from * @param _toReserveToken contract address of the reserve token to convert to * @param _amount amount of tokens received from the user * * @return amount of tokens that the user will receive * @return amount of tokens that the user will pay as fee */ function getCrossReserveReturn(IERC20Token _fromReserveToken, IERC20Token _toReserveToken, uint256 _amount) public view active validReserve(_fromReserveToken) validReserve(_toReserveToken) returns (uint256, uint256) { Reserve storage fromReserve = reserves[_fromReserveToken]; Reserve storage toReserve = reserves[_toReserveToken]; require(fromReserve.isSaleEnabled); // validate input IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.calculateCrossReserveReturn( getReserveBalance(_fromReserveToken), fromReserve.ratio, getReserveBalance(_toReserveToken), toReserve.ratio, _amount); uint256 finalAmount = getFinalAmount(amount, 2); // return the amount minus the conversion fee and the conversion fee // the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token) return (finalAmount, amount - finalAmount); } /** * @dev converts a specific amount of _fromToken to _toToken * can only be called by the bancor network contract * * @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 convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public only(BANCOR_NETWORK) conversionsAllowed greaterThanZero(_minReturn) returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its reserves if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); uint256 amount; uint256 feeAmount; // conversion between 2 reserves (amount, feeAmount) = getCrossReserveReturn(_fromToken, _toToken, _amount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update the source token virtual balance if relevant Reserve storage fromReserve = reserves[_fromToken]; if (fromReserve.isVirtualBalanceEnabled) fromReserve.virtualBalance = fromReserve.virtualBalance.add(_amount); // update the target token virtual balance if relevant Reserve storage toReserve = reserves[_toToken]; if (toReserve.isVirtualBalanceEnabled) toReserve.virtualBalance = toReserve.virtualBalance.sub(amount); // ensure that the trade won't deplete the reserve balance uint256 toReserveBalance = getReserveBalance(_toToken); assert(amount < toReserveBalance); // transfer funds from the caller in the from reserve token ensureTransferFrom(_fromToken, msg.sender, this, _amount); // transfer funds to the caller in the to reserve token // the transfer might fail if virtual balance is enabled ensureTransferFrom(_toToken, this, msg.sender, amount); // dispatch the conversion event // the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token) dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount); // dispatch price data updates for the smart token / both reserves emit PriceDataUpdate(_fromToken, token.totalSupply(), _fromToken.balanceOf(this), fromReserve.ratio); emit PriceDataUpdate(_toToken, token.totalSupply(), _toToken.balanceOf(this), toReserve.ratio); return amount; } /** * @dev buys the token by depositing one of its reserve tokens * * @param _reserveToken reserve token contract address * @param _depositAmount amount to deposit (in the reserve 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 _reserveToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) { uint256 amount; uint256 feeAmount; (amount, feeAmount) = getPurchaseReturn(_reserveToken, _depositAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update virtual balance if relevant Reserve storage reserve = reserves[_reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.add(_depositAmount); // transfer funds from the caller in the reserve token ensureTransferFrom(_reserveToken, msg.sender, this, _depositAmount); // issue new funds to the caller in the smart token token.issue(msg.sender, amount); // dispatch the conversion event dispatchConversionEvent(_reserveToken, token, _depositAmount, amount, feeAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(_reserveToken, token.totalSupply(), _reserveToken.balanceOf(this), reserve.ratio); return amount; } /** * @dev sells the token by withdrawing from one of its reserve tokens * * @param _reserveToken reserve 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 _reserveToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input uint256 amount; uint256 feeAmount; (amount, feeAmount) = getSaleReturn(_reserveToken, _sellAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // ensure that the trade will only deplete the reserve balance if the total supply is depleted as well uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = _reserveToken.balanceOf(this); assert(amount < reserveBalance || (amount == reserveBalance && _sellAmount == tokenSupply)); // update virtual balance if relevant Reserve storage reserve = reserves[_reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.sub(amount); // destroy _sellAmount from the caller's balance in the smart token token.destroy(msg.sender, _sellAmount); // transfer funds to the caller in the reserve token ensureTransferFrom(_reserveToken, this, msg.sender, amount); // dispatch the conversion event dispatchConversionEvent(token, _reserveToken, _sellAmount, amount, feeAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(_reserveToken, token.totalSupply(), _reserveToken.balanceOf(this), reserve.ratio); return amount; } /** * @dev converts a specific amount of _fromToken to _toToken * note that prior to version 16, you should use 'convert' instead * * @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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return conversion return amount */ function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) { IERC20Token[] memory path = new IERC20Token[](3); (path[0], path[1], path[2]) = (_fromToken, token, _toToken); return quickConvert2(path, _amount, _minReturn, _affiliateAccount, _affiliateFee); } /** * @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 * note that prior to version 16, you should use 'quickConvert' instead * * @param _path conversion path, see conversion path format in the BancorNetwork 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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) { return quickConvertPrioritized2(_path, _amount, _minReturn, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee); } /** * @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 * note that prior to version 16, you should use 'quickConvertPrioritized' instead * * @param _path conversion path, see conversion path format in the BancorNetwork 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 * @param _signature an array of the following elements: * [0] uint256 custom value that was signed for prioritized conversion; must be equal to _amount * [1] uint256 if the current block exceeded the given parameter - it is cancelled * [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit * [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit * [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function quickConvertPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) { require(_signature.length == 0 || _signature[0] == _amount); IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK)); // we need to transfer the source tokens from the caller to the BancorNetwork contract, // so it can execute the conversion on behalf of the caller if (msg.value == 0) { // not ETH, send the source tokens to the BancorNetwork contract // if the token is the smart token, no allowance is required - destroy the tokens // from the caller and issue them to the BancorNetwork contract if (_path[0] == token) { token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract } else { // otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract ensureTransferFrom(_path[0], msg.sender, bancorNetwork, _amount); } } // execute the conversion and pass on the ETH with the call return bancorNetwork.convertForPrioritized4.value(msg.value)(_path, _amount, _minReturn, msg.sender, _signature, _affiliateAccount, _affiliateFee); } /** * @dev allows a user to convert BNT that was sent from another blockchain into any other * token on the BancorNetwork without specifying the amount of BNT to be converted, but * rather by providing the xTransferId which allows us to get the amount from BancorX. * note that prior to version 16, you should use 'completeXConversion' instead * * @param _path conversion path, see conversion path format in the BancorNetwork contract * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _signature an array of the following elements: * [0] uint256 custom value that was signed for prioritized conversion; must be equal to _conversionId * [1] uint256 if the current block exceeded the given parameter - it is cancelled * [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit * [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit * [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature * * @return tokens issued in return */ function completeXConversion2( IERC20Token[] _path, uint256 _minReturn, uint256 _conversionId, uint256[] memory _signature ) public returns (uint256) { // verify that the custom value (if valid) is equal to _conversionId require(_signature.length == 0 || _signature[0] == _conversionId); IBancorX bancorX = IBancorX(addressOf(BANCOR_X)); IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK)); // verify that the first token in the path is BNT require(_path[0] == addressOf(BNT_TOKEN)); // get conversion amount from BancorX contract uint256 amount = bancorX.getXTransferAmount(_conversionId, msg.sender); // send BNT from msg.sender to the BancorNetwork contract token.destroy(msg.sender, amount); token.issue(bancorNetwork, amount); return bancorNetwork.convertForPrioritized4(_path, amount, _minReturn, msg.sender, _signature, address(0), 0); } /** * @dev returns whether or not the caller is an administrator */ function isAdmin() internal view returns (bool) { return msg.sender == owner || msg.sender == manager; } /** * @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return * true on success but revert on failure instead * * @param _token the token to transfer * @param _from the address to transfer the tokens from * @param _to the address to transfer the tokens to * @param _amount the amount to transfer */ function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private { // We must assume that functions `transfer` and `transferFrom` do not return anything, // because not all tokens abide the requirement of the ERC20 standard to return success or failure. // This is because in the current compiler version, the calling contract can handle more returned data than expected but not less. // This may change in the future, so that the calling contract will revert if the size of the data is not exactly what it expects. uint256 prevBalance = _token.balanceOf(_to); if (_from == address(this)) INonStandardERC20(_token).transfer(_to, _amount); else INonStandardERC20(_token).transferFrom(_from, _to, _amount); uint256 postBalance = _token.balanceOf(_to); require(postBalance > prevBalance); } /** * @dev buys the token with all reserve tokens using the same percentage * for example, if the caller increases the supply by 10%, * then it will cost an amount equal to 10% of each reserve token balance * note that the function can be called only when conversions are enabled * * @param _amount amount to increase the supply by (in the smart token) */ function fund(uint256 _amount) public conversionsAllowed multipleReservesOnly { uint256 supply = token.totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); // iterate through the reserve tokens and transfer a percentage equal to the ratio between _amount // and the total supply in each reserve from the caller to the converter IERC20Token reserveToken; uint256 reserveBalance; uint256 reserveAmount; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; reserveBalance = reserveToken.balanceOf(this); reserveAmount = formula.calculateFundCost(supply, reserveBalance, totalReserveRatio, _amount); // update virtual balance if relevant Reserve storage reserve = reserves[reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.add(reserveAmount); // transfer funds from the caller in the reserve token ensureTransferFrom(reserveToken, msg.sender, this, reserveAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(reserveToken, supply + _amount, reserveBalance + reserveAmount, reserve.ratio); } // issue new funds to the caller in the smart token token.issue(msg.sender, _amount); } /** * @dev sells the token for all reserve tokens using the same percentage * for example, if the holder sells 10% of the supply, * then they will receive 10% of each reserve token balance in return * note that the function can be called also when conversions are disabled * * @param _amount amount to liquidate (in the smart token) */ function liquidate(uint256 _amount) public multipleReservesOnly { uint256 supply = token.totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); // destroy _amount from the caller's balance in the smart token token.destroy(msg.sender, _amount); // iterate through the reserve tokens and send a percentage equal to the ratio between _amount // and the total supply from each reserve balance to the caller IERC20Token reserveToken; uint256 reserveBalance; uint256 reserveAmount; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; reserveBalance = reserveToken.balanceOf(this); reserveAmount = formula.calculateLiquidateReturn(supply, reserveBalance, totalReserveRatio, _amount); // update virtual balance if relevant Reserve storage reserve = reserves[reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.sub(reserveAmount); // transfer funds to the caller in the reserve token ensureTransferFrom(reserveToken, this, msg.sender, reserveAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(reserveToken, supply - _amount, reserveBalance - reserveAmount, reserve.ratio); } } /** * @dev helper, dispatches the Conversion event * * @param _fromToken ERC20 token to convert from * @param _toToken ERC20 token to convert to * @param _amount amount purchased/sold (in the source token) * @param _returnAmount amount returned (in the target token) */ function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private { // fee amount is converted to 255 bits - // negative amount means the fee is taken from the source token, positive amount means its taken from the target token // currently the fee is always taken from the target token // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow assert(_feeAmount < 2 ** 255); emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount)); } function getSignature( uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (uint256[] memory) { if (_v == 0x0 && _r == 0x0 && _s == 0x0) return new uint256[](0); uint256[] memory signature = new uint256[](5); signature[0] = _customVal; signature[1] = _block; signature[2] = uint256(_v); signature[3] = uint256(_r); signature[4] = uint256(_s); return signature; } /** * @dev deprecated, backward compatibility */ function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertInternal(_fromToken, _toToken, _amount, _minReturn); } /** * @dev deprecated, backward compatibility */ function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convert2(_fromToken, _toToken, _amount, _minReturn, address(0), 0); } /** * @dev deprecated, backward compatibility */ function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return quickConvert2(_path, _amount, _minReturn, address(0), 0); } /** * @dev deprecated, backward compatibility */ function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { return quickConvertPrioritized2(_path, _amount, _minReturn, getSignature(_amount, _block, _v, _r, _s), address(0), 0); } /** * @dev deprecated, backward compatibility */ function completeXConversion(IERC20Token[] _path, uint256 _minReturn, uint256 _conversionId, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public returns (uint256) { return completeXConversion2(_path, _minReturn, _conversionId, getSignature(_conversionId, _block, _v, _r, _s)); } /** * @dev deprecated, backward compatibility */ function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool) { Reserve storage reserve = reserves[_address]; return(reserve.virtualBalance, reserve.ratio, reserve.isVirtualBalanceEnabled, reserve.isSaleEnabled, reserve.isSet); } /** * @dev deprecated, backward compatibility */ function connectorTokens(uint256 _index) public view returns (IERC20Token) { return BancorConverter.reserveTokens[_index]; } /** * @dev deprecated, backward compatibility */ function connectorTokenCount() public view returns (uint16) { return reserveTokenCount(); } /** * @dev deprecated, backward compatibility */ function addConnector(IERC20Token _token, uint32 _weight, bool /*_enableVirtualBalance*/) public { addReserve(_token, _weight); } /** * @dev deprecated, backward compatibility */ function updateConnector(IERC20Token _connectorToken, uint32 /*_weight*/, bool /*_enableVirtualBalance*/, uint256 _virtualBalance) public { updateReserveVirtualBalance(_connectorToken, _virtualBalance); } /** * @dev deprecated, backward compatibility */ function disableConnectorSale(IERC20Token _connectorToken, bool _disable) public { disableReserveSale(_connectorToken, _disable); } /** * @dev deprecated, backward compatibility */ function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256) { return getReserveBalance(_connectorToken); } /** * @dev deprecated, backward compatibility */ function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _amount) public view returns (uint256, uint256) { return getCrossReserveReturn(_fromConnectorToken, _toConnectorToken, _amount); } }
File 4 of 14: 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 5 of 14: BancorConverter
// File: contracts/token/interfaces/IERC20Token.sol pragma solidity 0.4.26; /* 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) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} 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); } // File: contracts/utility/interfaces/IWhitelist.sol pragma solidity 0.4.26; /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } // File: contracts/converter/interfaces/IBancorConverter.sol pragma solidity 0.4.26; /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256); function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256); function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256); function conversionsEnabled() public view returns (bool) {this;} function conversionWhitelist() public view returns (IWhitelist) {this;} function conversionFee() public view returns (uint32) {this;} function reserves(address _address) public view returns (uint256, uint32, bool, bool, bool) {_address; this;} function getReserveBalance(IERC20Token _reserveToken) public view returns (uint256); function reserveTokens(uint256 _index) public view returns (IERC20Token) {_index; this;} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool); function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256); function connectorTokens(uint256 _index) public view returns (IERC20Token); function connectorTokenCount() public view returns (uint16); } // File: contracts/converter/interfaces/IBancorConverterUpgrader.sol pragma solidity 0.4.26; /* Bancor Converter Upgrader interface */ contract IBancorConverterUpgrader { function upgrade(bytes32 _version) public; function upgrade(uint16 _version) public; } // File: contracts/converter/interfaces/IBancorFormula.sol pragma solidity 0.4.26; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); // deprecated, backward compatibility function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: contracts/IBancorNetwork.sol pragma solidity 0.4.26; /* Bancor Network interface */ contract IBancorNetwork { function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertForPrioritized4( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); // deprecated, backward compatibility function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256); // deprecated, backward compatibility function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public returns (uint256); // deprecated, backward compatibility function convertForPrioritized3( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s ) public payable returns (uint256); } // File: contracts/FeatureIds.sol pragma solidity 0.4.26; /** * @dev Id definitions for bancor contract features * * Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } // File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* 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) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(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); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Managed.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract management * Note that a managed contract must also have an owner */ contract Managed is Owned { address public manager; address public newManager; /** * @dev triggered when the manager is updated * * @param _prevManager previous manager * @param _newManager new manager */ event ManagerUpdate(address indexed _prevManager, address indexed _newManager); /** * @dev initializes a new Managed instance */ constructor() public { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } // allows execution by either the owner or the manager only modifier ownerOrManagerOnly { require(msg.sender == owner || 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 ownerOrManagerOnly { require(_newManager != manager); newManager = _newManager; } /** * @dev used by a new manager to accept a management transfer */ function acceptManagement() public { require(msg.sender == newManager); emit ManagerUpdate(manager, newManager); manager = newManager; newManager = address(0); } } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() 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)); _; } } // File: contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.4.26; /* Contract Registry interface */ contract IContractRegistry { function addressOf(bytes32 _contractName) public view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address); } // File: contracts/utility/ContractRegistryClient.sol pragma solidity 0.4.26; /** * @dev Base contract for ContractRegistry clients */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures"; bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit"; bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory"; bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public adminOnly; // only an administrator can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { require(msg.sender == addressOf(_contractName)); _; } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(_registry) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(!adminOnly || isAdmin()); // get the new contract-registry address newRegistry = addressOf(CONTRACT_REGISTRY); // verify that the new contract-registry is different and not zero require(newRegistry != address(registry) && newRegistry != address(0)); // verify that the new contract-registry is pointing to a non-zero contract-registry require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0)); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = IContractRegistry(newRegistry); } /** * @dev restores the previous contract-registry */ function restoreRegistry() public { // verify that this function is permitted require(isAdmin()); // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _adminOnly indicates whether or not permission is restricted to administrator only */ function restrictRegistryUpdate(bool _adminOnly) public { // verify that this function is permitted require(adminOnly != _adminOnly && isAdmin()); // change the permission to update the contract-registry adminOnly = _adminOnly; } /** * @dev returns whether or not the caller is an administrator */ function isAdmin() internal view returns (bool) { return msg.sender == owner; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: contracts/utility/interfaces/IContractFeatures.sol pragma solidity 0.4.26; /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } // File: contracts/utility/interfaces/IAddressList.sol pragma solidity 0.4.26; /* Address list interface */ contract IAddressList { mapping (address => bool) public listedAddresses; } // File: contracts/token/interfaces/ISmartToken.sol pragma solidity 0.4.26; /* 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; } // File: contracts/token/interfaces/ISmartTokenController.sol pragma solidity 0.4.26; /* Smart Token Controller interface */ contract ISmartTokenController { function claimTokens(address _from, uint256 _amount) public; function token() public view returns (ISmartToken) {this;} } // File: contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.4.26; /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/token/interfaces/INonStandardERC20.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve */ contract INonStandardERC20 { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public; } // File: contracts/utility/TokenHolder.sol pragma solidity 0.4.26; /** * @dev 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. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, Owned, Utils { /** * @dev initializes a new TokenHolder instance */ constructor() 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) { INonStandardERC20(_token).transfer(_to, _amount); } } // File: contracts/token/SmartTokenController.sol pragma solidity 0.4.26; /** * @dev 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 ISmartTokenController, TokenHolder { ISmartToken public token; // Smart Token contract address public bancorX; // BancorX contract /** * @dev initializes a new SmartTokenController instance * * @param _token smart token governed by the controller */ constructor(ISmartToken _token) public validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { require(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { require(token.owner() != address(this)); _; } /** * @dev allows transferring the token ownership * the new owner needs 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 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); } /** * @dev allows the associated BancorX contract to claim tokens from any address (so that users * dont have to first give allowance when calling BancorX) * * @param _from address to claim the tokens from * @param _amount the amount of tokens to claim */ function claimTokens(address _from, uint256 _amount) public { // only the associated BancorX contract may call this method require(msg.sender == bancorX); // destroy the tokens belonging to _from, and issue the same amount to bancorX token.destroy(_from, _amount); token.issue(msg.sender, _amount); } /** * @dev allows the owner to set the associated BancorX contract * @param _bancorX BancorX contract */ function setBancorX(address _bancorX) public ownerOnly { bancorX = _bancorX; } } // File: contracts/token/interfaces/IEtherToken.sol pragma solidity 0.4.26; /* Ether Token interface */ contract IEtherToken is ITokenHolder, IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function withdrawTo(address _to, uint256 _amount) public; } // File: contracts/bancorx/interfaces/IBancorX.sol pragma solidity 0.4.26; contract IBancorX { function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public; function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256); } // File: contracts/converter/BancorConverter.sol pragma solidity 0.4.26; /** * @dev Bancor Converter * * The Bancor converter allows for conversions between a Smart Token and other ERC20 tokens and between different ERC20 tokens and themselves. * * The ERC20 reserve balance can be virtual, meaning that conversions between reserve tokens are based on the virtual balance instead of relying on the actual reserve balance. * * This mechanism opens the possibility to create different financial tools (for example, lower slippage in conversions). * * The converter is upgradable (just like any SmartTokenController) and all upgrades are opt-in. * * 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 * - gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer * * Other potential solutions might include a commit/reveal based schemes * - Possibly add getters for the reserve fields so that the client won't need to rely on the order in the struct */ contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractRegistryClient, FeatureIds { using SafeMath for uint256; uint32 private constant RATIO_RESOLUTION = 1000000; uint64 private constant CONVERSION_FEE_RESOLUTION = 1000000; struct Reserve { uint256 virtualBalance; // reserve virtual balance uint32 ratio; // reserve ratio, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isSaleEnabled; // is sale of the reserve token enabled, can be set by the owner bool isSet; // used to tell if the mapping element is defined } /** * @dev version number */ uint16 public version = 23; string public converterType = 'bancor'; IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public reserveTokens; // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead) mapping (address => Reserve) public reserves; // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead) uint32 private totalReserveRatio = 0; // used to efficiently prevent increasing the total reserve ratio 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 /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken ERC20 token converted from * @param _toToken ERC20 token converted to * @param _trader wallet that initiated the trade * @param _amount amount converted, in fromToken * @param _return amount returned, minus conversion fee * @param _conversionFee conversion fee */ event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered after a conversion with new price data * * @param _connectorToken reserve token * @param _tokenSupply smart token supply * @param _connectorBalance reserve balance * @param _connectorWeight reserve ratio */ event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** * @dev triggered when conversions are enabled/disabled * * @param _conversionsEnabled true if conversions are enabled, false if not */ event ConversionsEnable(bool _conversionsEnabled); /** * @dev triggered when virtual balances are enabled/disabled * * @param _enabled true if virtual balances are enabled, false if not */ event VirtualBalancesEnable(bool _enabled); /** * @dev initializes a new BancorConverter instance * * @param _token smart token governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm * @param _reserveToken optional, initial reserve, allows defining the first reserve at deployment time * @param _reserveRatio optional, ratio for the initial reserve */ constructor( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _reserveToken, uint32 _reserveRatio ) ContractRegistryClient(_registry) public SmartTokenController(_token) validConversionFee(_maxConversionFee) { IContractFeatures features = IContractFeatures(addressOf(CONTRACT_FEATURES)); // initialize supported features if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_reserveToken != address(0)) addReserve(_reserveToken, _reserveRatio); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(IERC20Token _address) { require(reserves[_address].isSet); _; } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= CONVERSION_FEE_RESOLUTION); _; } // validates reserve ratio modifier validReserveRatio(uint32 _ratio) { require(_ratio > 0 && _ratio <= RATIO_RESOLUTION); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { require(conversionsEnabled); _; } // allows execution only if the total-supply of the token is greater than zero modifier totalSupplyGreaterThanZeroOnly { require(token.totalSupply() > 0); _; } // allows execution only on a multiple-reserve converter modifier multipleReservesOnly { require(reserveTokens.length > 1); _; } /** * @dev returns the number of reserve tokens defined * note that prior to version 17, you should use 'connectorTokenCount' instead * * @return number of reserve tokens */ function reserveTokenCount() public view returns (uint16) { return uint16(reserveTokens.length); } /** * @dev allows the owner to update & enable the conversion whitelist contract address * when set, only addresses that are whitelisted are actually allowed to use the converter * note that the whitelist check is actually done by the BancorNetwork contract * * @param _whitelist address of a whitelist contract */ function setConversionWhitelist(IWhitelist _whitelist) public ownerOnly notThis(_whitelist) { conversionWhitelist = _whitelist; } /** * @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 { if (conversionsEnabled == _disable) { conversionsEnabled = !_disable; emit ConversionsEnable(conversionsEnabled); } } /** * @dev allows transferring the token ownership * the new owner needs to accept the transfer * can only be called by the contract owner * note that token ownership can only be transferred while the owner is the converter upgrader contract * * @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly only(BANCOR_CONVERTER_UPGRADER) { super.transferTokenOwnership(_newOwner); } /** * @dev used by a new owner to accept a token ownership transfer * can only be called by the contract owner * note that token ownership can only be accepted if its total-supply is greater than zero */ function acceptTokenOwnership() public ownerOnly totalSupplyGreaterThanZeroOnly { super.acceptTokenOwnership(); } /** * @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 { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); emit ConversionFeeUpdate(conversionFee, _conversionFee); conversionFee = _conversionFee; } /** * @dev given a return amount, returns the amount minus the conversion fee * * @param _amount return amount * @param _magnitude 1 for standard conversion, 2 for cross reserve conversion * * @return return amount minus conversion fee */ function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) { return _amount.mul((CONVERSION_FEE_RESOLUTION - conversionFee) ** _magnitude).div(CONVERSION_FEE_RESOLUTION ** _magnitude); } /** * @dev withdraws tokens held by the converter and sends them to an account * can only be called by the owner * note that reserve tokens can only be withdrawn by the owner while the converter is inactive * unless the owner is the converter upgrader contract * * @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 { address converterUpgrader = addressOf(BANCOR_CONVERTER_UPGRADER); // if the token is not a reserve token, allow withdrawal // otherwise verify that the converter is inactive or that the owner is the upgrader contract require(!reserves[_token].isSet || token.owner() != address(this) || owner == converterUpgrader); super.withdrawTokens(_token, _to, _amount); } /** * @dev upgrades the converter to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership/acceptManagement on the new converter after the upgrade */ function upgrade() public ownerOnly { IBancorConverterUpgrader converterUpgrader = IBancorConverterUpgrader(addressOf(BANCOR_CONVERTER_UPGRADER)); transferOwnership(converterUpgrader); converterUpgrader.upgrade(version); acceptOwnership(); } /** * @dev defines a new reserve for the token * can only be called by the owner while the converter is inactive * note that prior to version 17, you should use 'addConnector' instead * * @param _token address of the reserve token * @param _ratio constant reserve ratio, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _ratio) public ownerOnly inactive validAddress(_token) notThis(_token) validReserveRatio(_ratio) { require(_token != token && !reserves[_token].isSet && totalReserveRatio + _ratio <= RATIO_RESOLUTION); // validate input reserves[_token].ratio = _ratio; reserves[_token].isVirtualBalanceEnabled = false; reserves[_token].virtualBalance = 0; reserves[_token].isSaleEnabled = true; reserves[_token].isSet = true; reserveTokens.push(_token); totalReserveRatio += _ratio; } /** * @dev updates a reserve's virtual balance * only used during an upgrade process * can only be called by the contract owner while the owner is the converter upgrader contract * note that prior to version 17, you should use 'updateConnector' instead * * @param _reserveToken address of the reserve token * @param _virtualBalance new reserve virtual balance, or 0 to disable virtual balance */ function updateReserveVirtualBalance(IERC20Token _reserveToken, uint256 _virtualBalance) public ownerOnly only(BANCOR_CONVERTER_UPGRADER) validReserve(_reserveToken) { Reserve storage reserve = reserves[_reserveToken]; reserve.isVirtualBalanceEnabled = _virtualBalance != 0; reserve.virtualBalance = _virtualBalance; } /** * @dev enables virtual balance for the reserves * virtual balance only affects conversions between reserve tokens * virtual balance of all reserves can only scale by the same factor, to keep the ratio between them the same * note that the balance is determined during the execution of this function and set statically - * meaning that it's not calculated dynamically based on the factor after each conversion * can only be called by the contract owner while the converter is active * * @param _scaleFactor percentage, 100-1000 (100 = no virtual balance, 1000 = virtual balance = actual balance * 10) */ function enableVirtualBalances(uint16 _scaleFactor) public ownerOnly active { // validate input require(_scaleFactor >= 100 && _scaleFactor <= 1000); bool enable = _scaleFactor != 100; // iterate through the reserves and scale their balance by the ratio provided, // or disable virtual balance altogether if a factor of 100% is passed in IERC20Token reserveToken; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; Reserve storage reserve = reserves[reserveToken]; reserve.isVirtualBalanceEnabled = enable; reserve.virtualBalance = enable ? reserveToken.balanceOf(this).mul(_scaleFactor).div(100) : 0; } emit VirtualBalancesEnable(enable); } /** * @dev disables converting from the given reserve token in case the reserve token got compromised * can only be called by the owner * note that converting to the token is still enabled regardless of this flag and it cannot be disabled by the owner * note that prior to version 17, you should use 'disableConnectorSale' instead * * @param _reserveToken reserve token contract address * @param _disable true to disable the token, false to re-enable it */ function disableReserveSale(IERC20Token _reserveToken, bool _disable) public ownerOnly validReserve(_reserveToken) { reserves[_reserveToken].isSaleEnabled = !_disable; } /** * @dev returns the reserve's ratio * added in version 22 * * @param _reserveToken reserve token contract address * * @return reserve ratio */ function getReserveRatio(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return reserves[_reserveToken].ratio; } /** * @dev returns the reserve's virtual balance if one is defined, otherwise returns the actual balance * note that prior to version 17, you should use 'getConnectorBalance' instead * * @param _reserveToken reserve token contract address * * @return reserve balance */ function getReserveBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { Reserve storage reserve = reserves[_reserveToken]; return reserve.isVirtualBalanceEnabled ? reserve.virtualBalance : _reserveToken.balanceOf(this); } /** * @dev calculates the expected return of converting a given amount of tokens * * @param _fromToken contract address of the token to convert from * @param _toToken contract address of the token to convert to * @param _amount amount of tokens received from the user * * @return amount of tokens that the user will receive * @return amount of tokens that the user will pay as fee */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its reserves if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // conversion between 2 reserves return getCrossReserveReturn(_fromToken, _toToken, _amount); } /** * @dev calculates the expected return of buying with a given amount of tokens * * @param _reserveToken contract address of the reserve token * @param _depositAmount amount of reserve-tokens received from the user * * @return amount of supply-tokens that the user will receive * @return amount of supply-tokens that the user will pay as fee */ function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount) public view active validReserve(_reserveToken) returns (uint256, uint256) { Reserve storage reserve = reserves[_reserveToken]; require(reserve.isSaleEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = _reserveToken.balanceOf(this); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount); uint256 finalAmount = getFinalAmount(amount, 1); // return the amount minus the conversion fee and the conversion fee return (finalAmount, amount - finalAmount); } /** * @dev calculates the expected return of selling a given amount of tokens * * @param _reserveToken contract address of the reserve token * @param _sellAmount amount of supply-tokens received from the user * * @return amount of reserve-tokens that the user will receive * @return amount of reserve-tokens that the user will pay as fee */ function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount) public view active validReserve(_reserveToken) returns (uint256, uint256) { Reserve storage reserve = reserves[_reserveToken]; uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = _reserveToken.balanceOf(this); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.calculateSaleReturn(tokenSupply, reserveBalance, reserve.ratio, _sellAmount); uint256 finalAmount = getFinalAmount(amount, 1); // return the amount minus the conversion fee and the conversion fee return (finalAmount, amount - finalAmount); } /** * @dev calculates the expected return of converting a given amount from one reserve to another * note that prior to version 17, you should use 'getCrossConnectorReturn' instead * * @param _fromReserveToken contract address of the reserve token to convert from * @param _toReserveToken contract address of the reserve token to convert to * @param _amount amount of tokens received from the user * * @return amount of tokens that the user will receive * @return amount of tokens that the user will pay as fee */ function getCrossReserveReturn(IERC20Token _fromReserveToken, IERC20Token _toReserveToken, uint256 _amount) public view active validReserve(_fromReserveToken) validReserve(_toReserveToken) returns (uint256, uint256) { Reserve storage fromReserve = reserves[_fromReserveToken]; Reserve storage toReserve = reserves[_toReserveToken]; require(fromReserve.isSaleEnabled); // validate input IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.calculateCrossReserveReturn( getReserveBalance(_fromReserveToken), fromReserve.ratio, getReserveBalance(_toReserveToken), toReserve.ratio, _amount); uint256 finalAmount = getFinalAmount(amount, 2); // return the amount minus the conversion fee and the conversion fee // the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token) return (finalAmount, amount - finalAmount); } /** * @dev converts a specific amount of _fromToken to _toToken * can only be called by the bancor network contract * * @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 convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public only(BANCOR_NETWORK) conversionsAllowed greaterThanZero(_minReturn) returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its reserves if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); uint256 amount; uint256 feeAmount; // conversion between 2 reserves (amount, feeAmount) = getCrossReserveReturn(_fromToken, _toToken, _amount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update the source token virtual balance if relevant Reserve storage fromReserve = reserves[_fromToken]; if (fromReserve.isVirtualBalanceEnabled) fromReserve.virtualBalance = fromReserve.virtualBalance.add(_amount); // update the target token virtual balance if relevant Reserve storage toReserve = reserves[_toToken]; if (toReserve.isVirtualBalanceEnabled) toReserve.virtualBalance = toReserve.virtualBalance.sub(amount); // ensure that the trade won't deplete the reserve balance uint256 toReserveBalance = getReserveBalance(_toToken); assert(amount < toReserveBalance); // transfer funds from the caller in the from reserve token ensureTransferFrom(_fromToken, msg.sender, this, _amount); // transfer funds to the caller in the to reserve token // the transfer might fail if virtual balance is enabled ensureTransferFrom(_toToken, this, msg.sender, amount); // dispatch the conversion event // the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token) dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount); // dispatch price data updates for the smart token / both reserves emit PriceDataUpdate(_fromToken, token.totalSupply(), _fromToken.balanceOf(this), fromReserve.ratio); emit PriceDataUpdate(_toToken, token.totalSupply(), _toToken.balanceOf(this), toReserve.ratio); return amount; } /** * @dev buys the token by depositing one of its reserve tokens * * @param _reserveToken reserve token contract address * @param _depositAmount amount to deposit (in the reserve 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 _reserveToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) { uint256 amount; uint256 feeAmount; (amount, feeAmount) = getPurchaseReturn(_reserveToken, _depositAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update virtual balance if relevant Reserve storage reserve = reserves[_reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.add(_depositAmount); // transfer funds from the caller in the reserve token ensureTransferFrom(_reserveToken, msg.sender, this, _depositAmount); // issue new funds to the caller in the smart token token.issue(msg.sender, amount); // dispatch the conversion event dispatchConversionEvent(_reserveToken, token, _depositAmount, amount, feeAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(_reserveToken, token.totalSupply(), _reserveToken.balanceOf(this), reserve.ratio); return amount; } /** * @dev sells the token by withdrawing from one of its reserve tokens * * @param _reserveToken reserve 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 _reserveToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input uint256 amount; uint256 feeAmount; (amount, feeAmount) = getSaleReturn(_reserveToken, _sellAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // ensure that the trade will only deplete the reserve balance if the total supply is depleted as well uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = _reserveToken.balanceOf(this); assert(amount < reserveBalance || (amount == reserveBalance && _sellAmount == tokenSupply)); // update virtual balance if relevant Reserve storage reserve = reserves[_reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.sub(amount); // destroy _sellAmount from the caller's balance in the smart token token.destroy(msg.sender, _sellAmount); // transfer funds to the caller in the reserve token ensureTransferFrom(_reserveToken, this, msg.sender, amount); // dispatch the conversion event dispatchConversionEvent(token, _reserveToken, _sellAmount, amount, feeAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(_reserveToken, token.totalSupply(), _reserveToken.balanceOf(this), reserve.ratio); return amount; } /** * @dev converts a specific amount of _fromToken to _toToken * note that prior to version 16, you should use 'convert' instead * * @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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return conversion return amount */ function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) { IERC20Token[] memory path = new IERC20Token[](3); (path[0], path[1], path[2]) = (_fromToken, token, _toToken); return quickConvert2(path, _amount, _minReturn, _affiliateAccount, _affiliateFee); } /** * @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 * note that prior to version 16, you should use 'quickConvert' instead * * @param _path conversion path, see conversion path format in the BancorNetwork 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 * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) { return quickConvertPrioritized2(_path, _amount, _minReturn, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee); } /** * @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 * note that prior to version 16, you should use 'quickConvertPrioritized' instead * * @param _path conversion path, see conversion path format in the BancorNetwork 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 * @param _signature an array of the following elements: * [0] uint256 custom value that was signed for prioritized conversion; must be equal to _amount * [1] uint256 if the current block exceeded the given parameter - it is cancelled * [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit * [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit * [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return tokens issued in return */ function quickConvertPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) { require(_signature.length == 0 || _signature[0] == _amount); IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK)); // we need to transfer the source tokens from the caller to the BancorNetwork contract, // so it can execute the conversion on behalf of the caller if (msg.value == 0) { // not ETH, send the source tokens to the BancorNetwork contract // if the token is the smart token, no allowance is required - destroy the tokens // from the caller and issue them to the BancorNetwork contract if (_path[0] == token) { token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract } else { // otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract ensureTransferFrom(_path[0], msg.sender, bancorNetwork, _amount); } } // execute the conversion and pass on the ETH with the call return bancorNetwork.convertForPrioritized4.value(msg.value)(_path, _amount, _minReturn, msg.sender, _signature, _affiliateAccount, _affiliateFee); } /** * @dev allows a user to convert BNT that was sent from another blockchain into any other * token on the BancorNetwork without specifying the amount of BNT to be converted, but * rather by providing the xTransferId which allows us to get the amount from BancorX. * note that prior to version 16, you should use 'completeXConversion' instead * * @param _path conversion path, see conversion path format in the BancorNetwork contract * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _signature an array of the following elements: * [0] uint256 custom value that was signed for prioritized conversion; must be equal to _conversionId * [1] uint256 if the current block exceeded the given parameter - it is cancelled * [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit * [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit * [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature * * @return tokens issued in return */ function completeXConversion2( IERC20Token[] _path, uint256 _minReturn, uint256 _conversionId, uint256[] memory _signature ) public returns (uint256) { // verify that the custom value (if valid) is equal to _conversionId require(_signature.length == 0 || _signature[0] == _conversionId); IBancorX bancorX = IBancorX(addressOf(BANCOR_X)); IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK)); // verify that the first token in the path is BNT require(_path[0] == addressOf(BNT_TOKEN)); // get conversion amount from BancorX contract uint256 amount = bancorX.getXTransferAmount(_conversionId, msg.sender); // send BNT from msg.sender to the BancorNetwork contract token.destroy(msg.sender, amount); token.issue(bancorNetwork, amount); return bancorNetwork.convertForPrioritized4(_path, amount, _minReturn, msg.sender, _signature, address(0), 0); } /** * @dev returns whether or not the caller is an administrator */ function isAdmin() internal view returns (bool) { return msg.sender == owner || msg.sender == manager; } /** * @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return * true on success but revert on failure instead * * @param _token the token to transfer * @param _from the address to transfer the tokens from * @param _to the address to transfer the tokens to * @param _amount the amount to transfer */ function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private { // We must assume that functions `transfer` and `transferFrom` do not return anything, // because not all tokens abide the requirement of the ERC20 standard to return success or failure. // This is because in the current compiler version, the calling contract can handle more returned data than expected but not less. // This may change in the future, so that the calling contract will revert if the size of the data is not exactly what it expects. uint256 prevBalance = _token.balanceOf(_to); if (_from == address(this)) INonStandardERC20(_token).transfer(_to, _amount); else INonStandardERC20(_token).transferFrom(_from, _to, _amount); uint256 postBalance = _token.balanceOf(_to); require(postBalance > prevBalance); } /** * @dev buys the token with all reserve tokens using the same percentage * for example, if the caller increases the supply by 10%, * then it will cost an amount equal to 10% of each reserve token balance * note that the function can be called only when conversions are enabled * * @param _amount amount to increase the supply by (in the smart token) */ function fund(uint256 _amount) public conversionsAllowed multipleReservesOnly { uint256 supply = token.totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); // iterate through the reserve tokens and transfer a percentage equal to the ratio between _amount // and the total supply in each reserve from the caller to the converter IERC20Token reserveToken; uint256 reserveBalance; uint256 reserveAmount; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; reserveBalance = reserveToken.balanceOf(this); reserveAmount = formula.calculateFundCost(supply, reserveBalance, totalReserveRatio, _amount); // update virtual balance if relevant Reserve storage reserve = reserves[reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.add(reserveAmount); // transfer funds from the caller in the reserve token ensureTransferFrom(reserveToken, msg.sender, this, reserveAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(reserveToken, supply + _amount, reserveBalance + reserveAmount, reserve.ratio); } // issue new funds to the caller in the smart token token.issue(msg.sender, _amount); } /** * @dev sells the token for all reserve tokens using the same percentage * for example, if the holder sells 10% of the supply, * then they will receive 10% of each reserve token balance in return * note that the function can be called also when conversions are disabled * * @param _amount amount to liquidate (in the smart token) */ function liquidate(uint256 _amount) public multipleReservesOnly { uint256 supply = token.totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); // destroy _amount from the caller's balance in the smart token token.destroy(msg.sender, _amount); // iterate through the reserve tokens and send a percentage equal to the ratio between _amount // and the total supply from each reserve balance to the caller IERC20Token reserveToken; uint256 reserveBalance; uint256 reserveAmount; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; reserveBalance = reserveToken.balanceOf(this); reserveAmount = formula.calculateLiquidateReturn(supply, reserveBalance, totalReserveRatio, _amount); // update virtual balance if relevant Reserve storage reserve = reserves[reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = reserve.virtualBalance.sub(reserveAmount); // transfer funds to the caller in the reserve token ensureTransferFrom(reserveToken, this, msg.sender, reserveAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(reserveToken, supply - _amount, reserveBalance - reserveAmount, reserve.ratio); } } /** * @dev helper, dispatches the Conversion event * * @param _fromToken ERC20 token to convert from * @param _toToken ERC20 token to convert to * @param _amount amount purchased/sold (in the source token) * @param _returnAmount amount returned (in the target token) */ function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private { // fee amount is converted to 255 bits - // negative amount means the fee is taken from the source token, positive amount means its taken from the target token // currently the fee is always taken from the target token // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow assert(_feeAmount < 2 ** 255); emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount)); } function getSignature( uint256 _customVal, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (uint256[] memory) { if (_v == 0x0 && _r == 0x0 && _s == 0x0) return new uint256[](0); uint256[] memory signature = new uint256[](5); signature[0] = _customVal; signature[1] = _block; signature[2] = uint256(_v); signature[3] = uint256(_r); signature[4] = uint256(_s); return signature; } /** * @dev deprecated, backward compatibility */ function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertInternal(_fromToken, _toToken, _amount, _minReturn); } /** * @dev deprecated, backward compatibility */ function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convert2(_fromToken, _toToken, _amount, _minReturn, address(0), 0); } /** * @dev deprecated, backward compatibility */ function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return quickConvert2(_path, _amount, _minReturn, address(0), 0); } /** * @dev deprecated, backward compatibility */ function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { return quickConvertPrioritized2(_path, _amount, _minReturn, getSignature(_amount, _block, _v, _r, _s), address(0), 0); } /** * @dev deprecated, backward compatibility */ function completeXConversion(IERC20Token[] _path, uint256 _minReturn, uint256 _conversionId, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public returns (uint256) { return completeXConversion2(_path, _minReturn, _conversionId, getSignature(_conversionId, _block, _v, _r, _s)); } /** * @dev deprecated, backward compatibility */ function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool) { Reserve storage reserve = reserves[_address]; return(reserve.virtualBalance, reserve.ratio, reserve.isVirtualBalanceEnabled, reserve.isSaleEnabled, reserve.isSet); } /** * @dev deprecated, backward compatibility */ function connectorTokens(uint256 _index) public view returns (IERC20Token) { return BancorConverter.reserveTokens[_index]; } /** * @dev deprecated, backward compatibility */ function connectorTokenCount() public view returns (uint16) { return reserveTokenCount(); } /** * @dev deprecated, backward compatibility */ function addConnector(IERC20Token _token, uint32 _weight, bool /*_enableVirtualBalance*/) public { addReserve(_token, _weight); } /** * @dev deprecated, backward compatibility */ function updateConnector(IERC20Token _connectorToken, uint32 /*_weight*/, bool /*_enableVirtualBalance*/, uint256 _virtualBalance) public { updateReserveVirtualBalance(_connectorToken, _virtualBalance); } /** * @dev deprecated, backward compatibility */ function disableConnectorSale(IERC20Token _connectorToken, bool _disable) public { disableReserveSale(_connectorToken, _disable); } /** * @dev deprecated, backward compatibility */ function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256) { return getReserveBalance(_connectorToken); } /** * @dev deprecated, backward compatibility */ function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _amount) public view returns (uint256, uint256) { return getCrossReserveReturn(_fromConnectorToken, _toConnectorToken, _amount); } }
File 6 of 14: Dai
// hevm: flattened sources of /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol pragma solidity =0.5.12; ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/lib.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.5.12; */ contract LibNote { event LogNote( bytes4 indexed sig, address indexed usr, bytes32 indexed arg1, bytes32 indexed arg2, bytes data ) anonymous; modifier note { _; assembly { // log an 'anonymous' event with a constant 6 words of calldata // and four indexed topics: selector, caller, arg1 and arg2 let mark := msize // end of memory ensures zero mstore(0x40, add(mark, 288)) // update free memory pointer mstore(mark, 0x20) // bytes type data offset mstore(add(mark, 0x20), 224) // bytes size (padded) calldatacopy(add(mark, 0x40), 0, 224) // bytes payload log4(mark, 288, // calldata shl(224, shr(224, calldataload(0))), // msg.sig caller, // msg.sender calldataload(4), // arg1 calldataload(36) // arg2 ) } } } ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol // Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.5.12; */ /* import "./lib.sol"; */ contract Dai is LibNote { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external note auth { wards[guy] = 1; } function deny(address guy) external note auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "Dai/not-authorized"); _; } // --- ERC20 Data --- string public constant name = "Dai Stablecoin"; string public constant symbol = "DAI"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); // --- Math --- 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); } // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; constructor(uint256 chainId_) public { wards[msg.sender] = 1; DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId_, address(this) )); } // --- Token --- function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad, "Dai/insufficient-balance"); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function mint(address usr, uint wad) external auth { balanceOf[usr] = add(balanceOf[usr], wad); totalSupply = add(totalSupply, wad); emit Transfer(address(0), usr, wad); } function burn(address usr, uint wad) external { require(balanceOf[usr] >= wad, "Dai/insufficient-balance"); if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) { require(allowance[usr][msg.sender] >= wad, "Dai/insufficient-allowance"); allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad); } balanceOf[usr] = sub(balanceOf[usr], wad); totalSupply = sub(totalSupply, wad); emit Transfer(usr, address(0), wad); } function approve(address usr, uint wad) external returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } // --- Alias --- function push(address usr, uint wad) external { transferFrom(msg.sender, usr, wad); } function pull(address usr, uint wad) external { transferFrom(usr, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) )); require(holder != address(0), "Dai/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit"); require(expiry == 0 || now <= expiry, "Dai/permit-expired"); require(nonce == nonces[holder]++, "Dai/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; allowance[holder][spender] = wad; emit Approval(holder, spender, wad); } }
File 7 of 14: MatchingMarket
/// matching_market.sol // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.5.12; 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; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } 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, address(this), sig); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } 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); } } } } 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); } contract EventfulMarket { event LogItemUpdate(uint id); event LogTrade(uint pay_amt, address indexed pay_gem, uint buy_amt, address indexed buy_gem); event LogMake( bytes32 indexed id, bytes32 indexed pair, address indexed maker, ERC20 pay_gem, ERC20 buy_gem, uint128 pay_amt, uint128 buy_amt, uint64 timestamp ); event LogBump( bytes32 indexed id, bytes32 indexed pair, address indexed maker, ERC20 pay_gem, ERC20 buy_gem, uint128 pay_amt, uint128 buy_amt, uint64 timestamp ); event LogTake( bytes32 id, bytes32 indexed pair, address indexed maker, ERC20 pay_gem, ERC20 buy_gem, address indexed taker, uint128 take_amt, uint128 give_amt, uint64 timestamp ); event LogKill( bytes32 indexed id, bytes32 indexed pair, address indexed maker, ERC20 pay_gem, ERC20 buy_gem, uint128 pay_amt, uint128 buy_amt, uint64 timestamp ); } contract SimpleMarket is EventfulMarket, DSMath { uint public last_offer_id; mapping (uint => OfferInfo) public offers; bool locked; struct OfferInfo { uint pay_amt; ERC20 pay_gem; uint buy_amt; ERC20 buy_gem; address owner; uint64 timestamp; } modifier can_buy(uint id) { require(isActive(id)); _; } modifier can_cancel(uint id) { require(isActive(id)); require(getOwner(id) == msg.sender); _; } modifier can_offer { _; } modifier synchronized { require(!locked); locked = true; _; locked = false; } function isActive(uint id) public view returns (bool active) { return offers[id].timestamp > 0; } function getOwner(uint id) public view returns (address owner) { return offers[id].owner; } function getOffer(uint id) public view returns (uint, ERC20, uint, ERC20) { OfferInfo memory offer = offers[id]; return (offer.pay_amt, offer.pay_gem, offer.buy_amt, offer.buy_gem); } // ---- Public entrypoints ---- // function bump(bytes32 id_) public can_buy(uint256(id_)) { uint256 id = uint256(id_); emit LogBump( id_, keccak256(abi.encodePacked(offers[id].pay_gem, offers[id].buy_gem)), offers[id].owner, offers[id].pay_gem, offers[id].buy_gem, uint128(offers[id].pay_amt), uint128(offers[id].buy_amt), offers[id].timestamp ); } // Accept given `quantity` of an offer. Transfers funds from caller to // offer maker, and from market to caller. function buy(uint id, uint quantity) public can_buy(id) synchronized returns (bool) { OfferInfo memory offer = offers[id]; uint spend = mul(quantity, offer.buy_amt) / offer.pay_amt; require(uint128(spend) == spend); require(uint128(quantity) == quantity); // For backwards semantic compatibility. if (quantity == 0 || spend == 0 || quantity > offer.pay_amt || spend > offer.buy_amt) { return false; } offers[id].pay_amt = sub(offer.pay_amt, quantity); offers[id].buy_amt = sub(offer.buy_amt, spend); require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) ); require( offer.pay_gem.transfer(msg.sender, quantity) ); emit LogItemUpdate(id); emit LogTake( bytes32(id), keccak256(abi.encodePacked(offer.pay_gem, offer.buy_gem)), offer.owner, offer.pay_gem, offer.buy_gem, msg.sender, uint128(quantity), uint128(spend), uint64(now) ); emit LogTrade(quantity, address(offer.pay_gem), spend, address(offer.buy_gem)); if (offers[id].pay_amt == 0) { delete offers[id]; } return true; } // Cancel an offer. Refunds offer maker. function cancel(uint id) public can_cancel(id) synchronized returns (bool success) { // read-only offer. Modify an offer by directly accessing offers[id] OfferInfo memory offer = offers[id]; delete offers[id]; require( offer.pay_gem.transfer(offer.owner, offer.pay_amt) ); emit LogItemUpdate(id); emit LogKill( bytes32(id), keccak256(abi.encodePacked(offer.pay_gem, offer.buy_gem)), offer.owner, offer.pay_gem, offer.buy_gem, uint128(offer.pay_amt), uint128(offer.buy_amt), uint64(now) ); success = true; } function kill(bytes32 id) public { require(cancel(uint256(id))); } function make( ERC20 pay_gem, ERC20 buy_gem, uint128 pay_amt, uint128 buy_amt ) public returns (bytes32 id) { return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem)); } // Make a new offer. Takes funds from the caller into market escrow. function offer(uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem) public can_offer synchronized returns (uint id) { require(uint128(pay_amt) == pay_amt); require(uint128(buy_amt) == buy_amt); require(pay_amt > 0); require(pay_gem != ERC20(0x0)); require(buy_amt > 0); require(buy_gem != ERC20(0x0)); require(pay_gem != buy_gem); OfferInfo memory info; info.pay_amt = pay_amt; info.pay_gem = pay_gem; info.buy_amt = buy_amt; info.buy_gem = buy_gem; info.owner = msg.sender; info.timestamp = uint64(now); id = _next_id(); offers[id] = info; require( pay_gem.transferFrom(msg.sender, address(this), pay_amt) ); emit LogItemUpdate(id); emit LogMake( bytes32(id), keccak256(abi.encodePacked(pay_gem, buy_gem)), msg.sender, pay_gem, buy_gem, uint128(pay_amt), uint128(buy_amt), uint64(now) ); } function take(bytes32 id, uint128 maxTakeAmount) public { require(buy(uint256(id), maxTakeAmount)); } function _next_id() internal returns (uint) { last_offer_id++; return last_offer_id; } } // Simple Market with a market lifetime. When the close_time has been reached, // offers can only be cancelled (offer and buy will throw). contract ExpiringMarket is DSAuth, SimpleMarket { uint64 public close_time; bool public stopped; // after close_time has been reached, no new offers are allowed modifier can_offer { require(!isClosed()); _; } // after close, no new buys are allowed modifier can_buy(uint id) { require(isActive(id)); require(!isClosed()); _; } // after close, anyone can cancel an offer modifier can_cancel(uint id) { require(isActive(id)); require((msg.sender == getOwner(id)) || isClosed()); _; } constructor(uint64 _close_time) public { close_time = _close_time; } function isClosed() public view returns (bool closed) { return stopped || getTime() > close_time; } function getTime() public view returns (uint64) { return uint64(now); } function stop() public auth { stopped = true; } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } contract MatchingEvents { event LogBuyEnabled(bool isEnabled); event LogMinSell(address pay_gem, uint min_amount); event LogMatchingEnabled(bool isEnabled); event LogUnsortedOffer(uint id); event LogSortedOffer(uint id); event LogInsert(address keeper, uint id); event LogDelete(address keeper, uint id); } contract MatchingMarket is MatchingEvents, ExpiringMarket, DSNote { bool public buyEnabled = true; //buy enabled bool public matchingEnabled = true; //true: enable matching, //false: revert to expiring market struct sortInfo { uint next; //points to id of next higher offer uint prev; //points to id of previous lower offer uint delb; //the blocknumber where this entry was marked for delete } mapping(uint => sortInfo) public _rank; //doubly linked lists of sorted offer ids mapping(address => mapping(address => uint)) public _best; //id of the highest offer for a token pair mapping(address => mapping(address => uint)) public _span; //number of offers stored for token pair in sorted orderbook mapping(address => uint) public _dust; //minimum sell amount for a token to avoid dust offers mapping(uint => uint) public _near; //next unsorted offer id uint _head; //first unsorted offer id uint public dustId; // id of the latest offer marked as dust constructor(uint64 close_time) ExpiringMarket(close_time) public { } // After close, anyone can cancel an offer modifier can_cancel(uint id) { require(isActive(id), "Offer was deleted or taken, or never existed."); require( isClosed() || msg.sender == getOwner(id) || id == dustId, "Offer can not be cancelled because user is not owner, and market is open, and offer sells required amount of tokens." ); _; } // ---- Public entrypoints ---- // function make( ERC20 pay_gem, ERC20 buy_gem, uint128 pay_amt, uint128 buy_amt ) public returns (bytes32) { return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem)); } function take(bytes32 id, uint128 maxTakeAmount) public { require(buy(uint256(id), maxTakeAmount)); } function kill(bytes32 id) public { require(cancel(uint256(id))); } // Make a new offer. Takes funds from the caller into market escrow. // // If matching is enabled: // * creates new offer without putting it in // the sorted list. // * available to authorized contracts only! // * keepers should call insert(id,pos) // to put offer in the sorted list. // // If matching is disabled: // * calls expiring market's offer(). // * available to everyone without authorization. // * no sorting is done. // function offer( uint pay_amt, //maker (ask) sell how much ERC20 pay_gem, //maker (ask) sell which token uint buy_amt, //taker (ask) buy how much ERC20 buy_gem //taker (ask) buy which token ) public returns (uint) { require(!locked, "Reentrancy attempt"); function (uint256,ERC20,uint256,ERC20) returns (uint256) fn = matchingEnabled ? _offeru : super.offer; return fn(pay_amt, pay_gem, buy_amt, buy_gem); } // Make a new offer. Takes funds from the caller into market escrow. function offer( uint pay_amt, //maker (ask) sell how much ERC20 pay_gem, //maker (ask) sell which token uint buy_amt, //maker (ask) buy how much ERC20 buy_gem, //maker (ask) buy which token uint pos //position to insert offer, 0 should be used if unknown ) public can_offer returns (uint) { return offer(pay_amt, pay_gem, buy_amt, buy_gem, pos, true); } function offer( uint pay_amt, //maker (ask) sell how much ERC20 pay_gem, //maker (ask) sell which token uint buy_amt, //maker (ask) buy how much ERC20 buy_gem, //maker (ask) buy which token uint pos, //position to insert offer, 0 should be used if unknown bool rounding //match "close enough" orders? ) public can_offer returns (uint) { require(!locked, "Reentrancy attempt"); require(_dust[address(pay_gem)] <= pay_amt); if (matchingEnabled) { return _matcho(pay_amt, pay_gem, buy_amt, buy_gem, pos, rounding); } return super.offer(pay_amt, pay_gem, buy_amt, buy_gem); } //Transfers funds from caller to offer maker, and from market to caller. function buy(uint id, uint amount) public can_buy(id) returns (bool) { require(!locked, "Reentrancy attempt"); function (uint256,uint256) returns (bool) fn = matchingEnabled ? _buys : super.buy; return fn(id, amount); } // Cancel an offer. Refunds offer maker. function cancel(uint id) public can_cancel(id) returns (bool success) { require(!locked, "Reentrancy attempt"); if (matchingEnabled) { if (isOfferSorted(id)) { require(_unsort(id)); } else { require(_hide(id)); } } return super.cancel(id); //delete the offer. } //insert offer into the sorted list //keepers need to use this function function insert( uint id, //maker (ask) id uint pos //position to insert into ) public returns (bool) { require(!locked, "Reentrancy attempt"); require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted require(isActive(id)); //make sure offers[id] is active _hide(id); //remove offer from unsorted offers list _sort(id, pos); //put offer into the sorted offers list emit LogInsert(msg.sender, id); return true; } //deletes _rank [id] // Function should be called by keepers. function del_rank(uint id) public returns (bool) { require(!locked, "Reentrancy attempt"); require(!isActive(id) && _rank[id].delb != 0 && _rank[id].delb < block.number - 10); delete _rank[id]; emit LogDelete(msg.sender, id); return true; } //set the minimum sell amount for a token // Function is used to avoid "dust offers" that have // very small amount of tokens to sell, and it would // cost more gas to accept the offer, than the value // of tokens received. function setMinSell( ERC20 pay_gem, //token to assign minimum sell amount to uint dust //maker (ask) minimum sell amount ) public auth note returns (bool) { _dust[address(pay_gem)] = dust; emit LogMinSell(address(pay_gem), dust); return true; } //returns the minimum sell amount for an offer function getMinSell( ERC20 pay_gem //token for which minimum sell amount is queried ) public view returns (uint) { return _dust[address(pay_gem)]; } //set buy functionality enabled/disabled function setBuyEnabled(bool buyEnabled_) public auth returns (bool) { buyEnabled = buyEnabled_; emit LogBuyEnabled(buyEnabled); return true; } //set matching enabled/disabled // If matchingEnabled true(default), then inserted offers are matched. // Except the ones inserted by contracts, because those end up // in the unsorted list of offers, that must be later sorted by // keepers using insert(). // If matchingEnabled is false then MatchingMarket is reverted to ExpiringMarket, // and matching is not done, and sorted lists are disabled. function setMatchingEnabled(bool matchingEnabled_) public auth returns (bool) { matchingEnabled = matchingEnabled_; emit LogMatchingEnabled(matchingEnabled); return true; } //return the best offer for a token pair // the best offer is the lowest one if it's an ask, // and highest one if it's a bid offer function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public view returns(uint) { return _best[address(sell_gem)][address(buy_gem)]; } //return the next worse offer in the sorted list // the worse offer is the higher one if its an ask, // a lower one if its a bid offer, // and in both cases the newer one if they're equal. function getWorseOffer(uint id) public view returns(uint) { return _rank[id].prev; } //return the next better offer in the sorted list // the better offer is in the lower priced one if its an ask, // the next higher priced one if its a bid offer // and in both cases the older one if they're equal. function getBetterOffer(uint id) public view returns(uint) { return _rank[id].next; } //return the amount of better offers for a token pair function getOfferCount(ERC20 sell_gem, ERC20 buy_gem) public view returns(uint) { return _span[address(sell_gem)][address(buy_gem)]; } //get the first unsorted offer that was inserted by a contract // Contracts can't calculate the insertion position of their offer because it is not an O(1) operation. // Their offers get put in the unsorted list of offers. // Keepers can calculate the insertion position offchain and pass it to the insert() function to insert // the unsorted offer into the sorted list. Unsorted offers will not be matched, but can be bought with buy(). function getFirstUnsortedOffer() public view returns(uint) { return _head; } //get the next unsorted offer // Can be used to cycle through all the unsorted offers. function getNextUnsortedOffer(uint id) public view returns(uint) { return _near[id]; } function isOfferSorted(uint id) public view returns(bool) { return _rank[id].next != 0 || _rank[id].prev != 0 || _best[address(offers[id].pay_gem)][address(offers[id].buy_gem)] == id; } function sellAllAmount(ERC20 pay_gem, uint pay_amt, ERC20 buy_gem, uint min_fill_amount) public returns (uint fill_amt) { require(!locked, "Reentrancy attempt"); uint offerId; while (pay_amt > 0) { //while there is amount to sell offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair require(offerId != 0); //Fails if there are not more offers // There is a chance that pay_amt is smaller than 1 wei of the other token if (pay_amt * 1 ether < wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) { break; //We consider that all amount is sold } if (pay_amt >= offers[offerId].buy_amt) { //If amount to sell is higher or equal than current offer amount to buy fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount bought to acumulator pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to sell take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer } else { // if lower uint256 baux = rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9; fill_amt = add(fill_amt, baux); //Add amount bought to acumulator take(bytes32(offerId), uint128(baux)); //We take the portion of the offer that we need pay_amt = 0; //All amount is sold } } require(fill_amt >= min_fill_amount); } function buyAllAmount(ERC20 buy_gem, uint buy_amt, ERC20 pay_gem, uint max_fill_amount) public returns (uint fill_amt) { require(!locked, "Reentrancy attempt"); uint offerId; while (buy_amt > 0) { //Meanwhile there is amount to buy offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair require(offerId != 0); // There is a chance that buy_amt is smaller than 1 wei of the other token if (buy_amt * 1 ether < wdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) { break; //We consider that all amount is sold } if (buy_amt >= offers[offerId].pay_amt) { //If amount to buy is higher or equal than current offer amount to sell fill_amt = add(fill_amt, offers[offerId].buy_amt); //Add amount sold to acumulator buy_amt = sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer } else { //if lower fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add amount sold to acumulator take(bytes32(offerId), uint128(buy_amt)); //We take the portion of the offer that we need buy_amt = 0; //All amount is bought } } require(fill_amt <= max_fill_amount); } function getBuyAmount(ERC20 buy_gem, ERC20 pay_gem, uint pay_amt) public view returns (uint fill_amt) { uint256 offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair while (pay_amt > offers[offerId].buy_amt) { fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount to buy accumulator pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to pay if (pay_amt > 0) { //If we still need more offers offerId = getWorseOffer(offerId); //We look for the next best offer require(offerId != 0); //Fails if there are not enough offers to complete } } fill_amt = add(fill_amt, rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9); //Add proportional amount of last offer to buy accumulator } function getPayAmount(ERC20 pay_gem, ERC20 buy_gem, uint buy_amt) public view returns (uint fill_amt) { uint256 offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair while (buy_amt > offers[offerId].pay_amt) { fill_amt = add(fill_amt, offers[offerId].buy_amt); //Add amount to pay accumulator buy_amt = sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy if (buy_amt > 0) { //If we still need more offers offerId = getWorseOffer(offerId); //We look for the next best offer require(offerId != 0); //Fails if there are not enough offers to complete } } fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add proportional amount of last offer to pay accumulator } // ---- Internal Functions ---- // function _buys(uint id, uint amount) internal returns (bool) { require(buyEnabled); if (amount == offers[id].pay_amt) { if (isOfferSorted(id)) { //offers[id] must be removed from sorted list because all of it is bought _unsort(id); }else{ _hide(id); } } require(super.buy(id, amount)); // If offer has become dust during buy, we cancel it if (isActive(id) && offers[id].pay_amt < _dust[address(offers[id].pay_gem)]) { dustId = id; //enable current msg.sender to call cancel(id) cancel(id); } return true; } //find the id of the next higher offer after offers[id] function _find(uint id) internal view returns (uint) { require( id > 0 ); address buy_gem = address(offers[id].buy_gem); address pay_gem = address(offers[id].pay_gem); uint top = _best[pay_gem][buy_gem]; uint old_top = 0; // Find the larger-than-id order whose successor is less-than-id. while (top != 0 && _isPricedLtOrEq(id, top)) { old_top = top; top = _rank[top].prev; } return old_top; } //find the id of the next higher offer after offers[id] function _findpos(uint id, uint pos) internal view returns (uint) { require(id > 0); // Look for an active order. while (pos != 0 && !isActive(pos)) { pos = _rank[pos].prev; } if (pos == 0) { //if we got to the end of list without a single active offer return _find(id); } else { // if we did find a nearby active offer // Walk the order book down from there... if(_isPricedLtOrEq(id, pos)) { uint old_pos; // Guaranteed to run at least once because of // the prior if statements. while (pos != 0 && _isPricedLtOrEq(id, pos)) { old_pos = pos; pos = _rank[pos].prev; } return old_pos; // ...or walk it up. } else { while (pos != 0 && !_isPricedLtOrEq(id, pos)) { pos = _rank[pos].next; } return pos; } } } //return true if offers[low] priced less than or equal to offers[high] function _isPricedLtOrEq( uint low, //lower priced offer's id uint high //higher priced offer's id ) internal view returns (bool) { return mul(offers[low].buy_amt, offers[high].pay_amt) >= mul(offers[high].buy_amt, offers[low].pay_amt); } //these variables are global only because of solidity local variable limit //match offers with taker offer, and execute token transactions function _matcho( uint t_pay_amt, //taker sell how much ERC20 t_pay_gem, //taker sell which token uint t_buy_amt, //taker buy how much ERC20 t_buy_gem, //taker buy which token uint pos, //position id bool rounding //match "close enough" orders? ) internal returns (uint id) { uint best_maker_id; //highest maker id uint t_buy_amt_old; //taker buy how much saved uint m_buy_amt; //maker offer wants to buy this much token uint m_pay_amt; //maker offer wants to sell this much token // there is at least one offer stored for token pair while (_best[address(t_buy_gem)][address(t_pay_gem)] > 0) { best_maker_id = _best[address(t_buy_gem)][address(t_pay_gem)]; m_buy_amt = offers[best_maker_id].buy_amt; m_pay_amt = offers[best_maker_id].pay_amt; // Ugly hack to work around rounding errors. Based on the idea that // the furthest the amounts can stray from their "true" values is 1. // Ergo the worst case has t_pay_amt and m_pay_amt at +1 away from // their "correct" values and m_buy_amt and t_buy_amt at -1. // Since (c - 1) * (d - 1) > (a + 1) * (b + 1) is equivalent to // c * d > a * b + a + b + c + d, we write... if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) + (rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0)) { break; } // ^ The `rounding` parameter is a compromise borne of a couple days // of discussion. buy(best_maker_id, min(m_pay_amt, t_buy_amt)); t_buy_amt_old = t_buy_amt; t_buy_amt = sub(t_buy_amt, min(m_pay_amt, t_buy_amt)); t_pay_amt = mul(t_buy_amt, t_pay_amt) / t_buy_amt_old; if (t_pay_amt == 0 || t_buy_amt == 0) { break; } } if (t_buy_amt > 0 && t_pay_amt > 0 && t_pay_amt >= _dust[address(t_pay_gem)]) { //new offer should be created id = super.offer(t_pay_amt, t_pay_gem, t_buy_amt, t_buy_gem); //insert offer into the sorted list _sort(id, pos); } } // Make a new offer without putting it in the sorted list. // Takes funds from the caller into market escrow. // ****Available to authorized contracts only!********** // Keepers should call insert(id,pos) to put offer in the sorted list. function _offeru( uint pay_amt, //maker (ask) sell how much ERC20 pay_gem, //maker (ask) sell which token uint buy_amt, //maker (ask) buy how much ERC20 buy_gem //maker (ask) buy which token ) internal returns (uint id) { require(_dust[address(pay_gem)] <= pay_amt); id = super.offer(pay_amt, pay_gem, buy_amt, buy_gem); _near[id] = _head; _head = id; emit LogUnsortedOffer(id); } //put offer into the sorted list function _sort( uint id, //maker (ask) id uint pos //position to insert into ) internal { require(isActive(id)); ERC20 buy_gem = offers[id].buy_gem; ERC20 pay_gem = offers[id].pay_gem; uint prev_id; //maker (ask) id pos = pos == 0 || offers[pos].pay_gem != pay_gem || offers[pos].buy_gem != buy_gem || !isOfferSorted(pos) ? _find(id) : _findpos(id, pos); if (pos != 0) { //offers[id] is not the highest offer //requirement below is satisfied by statements above //require(_isPricedLtOrEq(id, pos)); prev_id = _rank[pos].prev; _rank[pos].prev = id; _rank[id].next = pos; } else { //offers[id] is the highest offer prev_id = _best[address(pay_gem)][address(buy_gem)]; _best[address(pay_gem)][address(buy_gem)] = id; } if (prev_id != 0) { //if lower offer does exist //requirement below is satisfied by statements above //require(!_isPricedLtOrEq(id, prev_id)); _rank[prev_id].next = id; _rank[id].prev = prev_id; } _span[address(pay_gem)][address(buy_gem)]++; emit LogSortedOffer(id); } // Remove offer from the sorted list (does not cancel offer) function _unsort( uint id //id of maker (ask) offer to remove from sorted list ) internal returns (bool) { address buy_gem = address(offers[id].buy_gem); address pay_gem = address(offers[id].pay_gem); require(_span[pay_gem][buy_gem] > 0); require(_rank[id].delb == 0 && //assert id is in the sorted list isOfferSorted(id)); if (id != _best[pay_gem][buy_gem]) { // offers[id] is not the highest offer require(_rank[_rank[id].next].prev == id); _rank[_rank[id].next].prev = _rank[id].prev; } else { //offers[id] is the highest offer _best[pay_gem][buy_gem] = _rank[id].prev; } if (_rank[id].prev != 0) { //offers[id] is not the lowest offer require(_rank[_rank[id].prev].next == id); _rank[_rank[id].prev].next = _rank[id].next; } _span[pay_gem][buy_gem]--; _rank[id].delb = block.number; //mark _rank[id] for deletion return true; } //Hide offer from the unsorted order book (does not cancel offer) function _hide( uint id //id of maker offer to remove from unsorted list ) internal returns (bool) { uint uid = _head; //id of an offer in unsorted offers list uint pre = uid; //id of previous offer in unsorted offers list require(!isOfferSorted(id)); //make sure offer id is not in sorted offers list if (_head == id) { //check if offer is first offer in unsorted offers list _head = _near[id]; //set head to new first unsorted offer _near[id] = 0; //delete order from unsorted order list return true; } while (uid > 0 && uid != id) { //find offer in unsorted order list pre = uid; uid = _near[uid]; } if (uid != id) { //did not find offer id in unsorted offers list return false; } _near[pre] = _near[id]; //set previous unsorted offer to point to offer after offer id _near[id] = 0; //delete order from unsorted order list return true; } }
File 8 of 14: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub // 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.18; contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } 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) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */
File 9 of 14: ContractRegistry
pragma solidity ^0.4.24; // File: contracts/utility/interfaces/IOwned.sol /* 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; } // File: contracts/utility/Owned.sol /* 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 */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(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); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Utils.sol /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() 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; } } // File: contracts/utility/interfaces/IContractRegistry.sol /* Contract Registry interface */ contract IContractRegistry { function addressOf(bytes32 _contractName) public view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address); } // File: contracts/ContractIds.sol /** Id definitions for bancor contracts Can be used in conjunction with the contract registry to get contract addresses */ contract ContractIds { // generic bytes32 public constant CONTRACT_FEATURES = "ContractFeatures"; bytes32 public constant CONTRACT_REGISTRY = "ContractRegistry"; // bancor logic bytes32 public constant BANCOR_NETWORK = "BancorNetwork"; bytes32 public constant BANCOR_FORMULA = "BancorFormula"; bytes32 public constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit"; bytes32 public constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 public constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory"; // Ids of BNT converter and BNT token bytes32 public constant BNT_TOKEN = "BNTToken"; bytes32 public constant BNT_CONVERTER = "BNTConverter"; // Id of BancorX contract bytes32 public constant BANCOR_X = "BancorX"; } // File: contracts/utility/ContractRegistry.sol /** Contract Registry The contract registry keeps contract addresses by name. The owner can update contract addresses so that a contract name always points to the latest version of the given contract. Other contracts can query the registry to get updated addresses instead of depending on specific addresses. Note that contract names are limited to 32 bytes UTF8 encoded ASCII strings to optimize gas costs */ contract ContractRegistry is IContractRegistry, Owned, Utils, ContractIds { struct RegistryItem { address contractAddress; // contract address uint256 nameIndex; // index of the item in the list of contract names bool isSet; // used to tell if the mapping element is defined } mapping (bytes32 => RegistryItem) private items; // name -> RegistryItem mapping string[] public contractNames; // list of all registered contract names // triggered when an address pointed to by a contract name is modified event AddressUpdate(bytes32 indexed _contractName, address _contractAddress); /** @dev constructor */ constructor() public { registerAddress(ContractIds.CONTRACT_REGISTRY, address(this)); } /** @dev returns the number of items in the registry @return number of items */ function itemCount() public view returns (uint256) { return contractNames.length; } /** @dev returns the address associated with the given contract name @param _contractName contract name @return contract address */ function addressOf(bytes32 _contractName) public view returns (address) { return items[_contractName].contractAddress; } /** @dev registers a new address for the contract name in the registry @param _contractName contract name @param _contractAddress contract address */ function registerAddress(bytes32 _contractName, address _contractAddress) public ownerOnly validAddress(_contractAddress) { require(_contractName.length > 0); // validate input // update the address in the registry items[_contractName].contractAddress = _contractAddress; if (!items[_contractName].isSet) { // mark the item as set items[_contractName].isSet = true; // add the contract name to the name list uint256 i = contractNames.push(bytes32ToString(_contractName)); // update the item's index in the list items[_contractName].nameIndex = i - 1; } // dispatch the address update event emit AddressUpdate(_contractName, _contractAddress); } /** @dev removes an existing contract address from the registry @param _contractName contract name */ function unregisterAddress(bytes32 _contractName) public ownerOnly { require(_contractName.length > 0); // validate input // remove the address from the registry items[_contractName].contractAddress = address(0); // if there are multiple items in the registry, move the last element to the deleted element's position // and modify last element's registryItem.nameIndex in the items collection to point to the right position in contractNames if (contractNames.length > 1) { string memory lastContractNameString = contractNames[contractNames.length - 1]; uint256 unregisterIndex = items[_contractName].nameIndex; contractNames[unregisterIndex] = lastContractNameString; bytes32 lastContractName = stringToBytes32(lastContractNameString); RegistryItem storage registryItem = items[lastContractName]; registryItem.nameIndex = unregisterIndex; } // remove the last element from the name list contractNames.length--; // zero the deleted element's index items[_contractName].nameIndex = 0; // dispatch the address update event emit AddressUpdate(_contractName, address(0)); } /** @dev utility, converts bytes32 to a string note that the bytes32 argument is assumed to be UTF8 encoded ASCII string @return string representation of the given bytes32 argument */ function bytes32ToString(bytes32 _bytes) private pure returns (string) { bytes memory byteArray = new bytes(32); for (uint256 i; i < 32; i++) { byteArray[i] = _bytes[i]; } return string(byteArray); } // @dev utility, converts string to bytes32 function stringToBytes32(string memory _string) private pure returns (bytes32) { bytes32 result; assembly { result := mload(add(_string,32)) } return result; } // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address) { return addressOf(_contractName); } }
File 10 of 14: SmartToken
pragma solidity 0.4.26; // File: contracts/token/interfaces/IERC20Token.sol /* 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) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} 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); } // File: contracts/utility/Utils.sol /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() 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)); _; } } // File: contracts/utility/SafeMath.sol /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/token/ERC20Token.sol /** * @dev ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /** * @dev triggered when tokens are transferred between wallets * * @param _from source address * @param _to target address * @param _value transfer amount */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf * * @param _owner wallet that approves the allowance * @param _spender wallet that receives the allowance * @param _value allowance amount */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev initializes a new ERC20Token instance * * @param _name token name * @param _symbol token symbol * @param _decimals decimal points, for display purposes * @param _totalSupply total supply of token units */ constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; } /** * @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] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit 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] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit 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; emit Approval(msg.sender, _spender, _value); return true; } } // File: contracts/utility/interfaces/IOwned.sol /* 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) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/token/interfaces/ISmartToken.sol /* 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; } // File: contracts/utility/Owned.sol /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(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); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/interfaces/ITokenHolder.sol /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/token/interfaces/INonStandardERC20.sol /* ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve */ contract INonStandardERC20 { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public; } // File: contracts/utility/TokenHolder.sol /** * @dev 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. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, Owned, Utils { /** * @dev initializes a new TokenHolder instance */ constructor() 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) { INonStandardERC20(_token).transfer(_to, _amount); } } // File: contracts/token/SmartToken.sol /** * @dev Smart Token * * 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder { using SafeMath for uint256; string public version = '0.3'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not /** * @dev triggered when a smart token is deployed * the _token address is defined for forward compatibility, in case the event is trigger by a factory * * @param _token new smart token address */ event NewSmartToken(address _token); /** * @dev triggered when the total supply is increased * * @param _amount amount that gets added to the supply */ event Issuance(uint256 _amount); /** * @dev triggered when the total supply is decreased * * @param _amount amount that gets removed from the supply */ event Destruction(uint256 _amount); /** * @dev initializes a new SmartToken instance * * @param _name token name * @param _symbol token short symbol, minimum 1 character * @param _decimals for display purposes only */ constructor(string _name, string _symbol, uint8 _decimals) public ERC20Token(_name, _symbol, _decimals, 0) { emit 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 = totalSupply.add(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); emit Issuance(_amount); emit 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] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, this, _amount); emit 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 11 of 14: ContractFeatures
pragma solidity ^0.4.21; /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /** Contract Features Generic contract that allows every contract on the blockchain to define which features it supports. Other contracts can query this contract to find out whether a given contract on the blockchain supports a certain feature. Each contract type can define its own list of feature flags. Features can be only enabled/disabled by the contract they are defined for. Features should be defined by each contract type as bit flags, e.g. - uint256 public constant FEATURE1 = 1 << 0; uint256 public constant FEATURE2 = 1 << 1; uint256 public constant FEATURE3 = 1 << 2; ... */ contract ContractFeatures is IContractFeatures { mapping (address => uint256) private featureFlags; event FeaturesAddition(address indexed _address, uint256 _features); event FeaturesRemoval(address indexed _address, uint256 _features); /** @dev constructor */ function ContractFeatures() public { } /** @dev returns true if a given contract supports the given feature(s), false if not @param _contract contract address to check support for @param _features feature(s) to check for @return true if the contract supports the feature(s), false if not */ function isSupported(address _contract, uint256 _features) public view returns (bool) { return (featureFlags[_contract] & _features) == _features; } /** @dev allows a contract to enable/disable certain feature(s) @param _features feature(s) to enable/disable @param _enable true to enable the feature(s), false to disabled them */ function enableFeatures(uint256 _features, bool _enable) public { if (_enable) { if (isSupported(msg.sender, _features)) return; featureFlags[msg.sender] |= _features; emit FeaturesAddition(msg.sender, _features); } else { if (!isSupported(msg.sender, _features)) return; featureFlags[msg.sender] &= ~_features; emit FeaturesRemoval(msg.sender, _features); } } }
File 12 of 14: SmartToken
// File: contracts/token/interfaces/IERC20Token.sol pragma solidity 0.4.26; /* 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) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} 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); } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() 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)); _; } } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/token/ERC20Token.sol pragma solidity 0.4.26; /** * @dev ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /** * @dev triggered when tokens are transferred between wallets * * @param _from source address * @param _to target address * @param _value transfer amount */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf * * @param _owner wallet that approves the allowance * @param _spender wallet that receives the allowance * @param _value allowance amount */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev initializes a new ERC20Token instance * * @param _name token name * @param _symbol token symbol * @param _decimals decimal points, for display purposes * @param _totalSupply total supply of token units */ constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; } /** * @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] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit 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] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit 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; emit Approval(msg.sender, _spender, _value); return true; } } // File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* 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) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/token/interfaces/ISmartToken.sol pragma solidity 0.4.26; /* 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; } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(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); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.4.26; /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/token/interfaces/INonStandardERC20.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve */ contract INonStandardERC20 { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public; } // File: contracts/utility/TokenHolder.sol pragma solidity 0.4.26; /** * @dev 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. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, Owned, Utils { /** * @dev initializes a new TokenHolder instance */ constructor() 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) { INonStandardERC20(_token).transfer(_to, _amount); } } // File: contracts/token/SmartToken.sol pragma solidity 0.4.26; /** * @dev Smart Token * * 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder { using SafeMath for uint256; string public version = '0.3'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not /** * @dev triggered when a smart token is deployed * the _token address is defined for forward compatibility, in case the event is trigger by a factory * * @param _token new smart token address */ event NewSmartToken(address _token); /** * @dev triggered when the total supply is increased * * @param _amount amount that gets added to the supply */ event Issuance(uint256 _amount); /** * @dev triggered when the total supply is decreased * * @param _amount amount that gets removed from the supply */ event Destruction(uint256 _amount); /** * @dev initializes a new SmartToken instance * * @param _name token name * @param _symbol token short symbol, minimum 1 character * @param _decimals for display purposes only */ constructor(string _name, string _symbol, uint8 _decimals) public ERC20Token(_name, _symbol, _decimals, 0) { emit 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 = totalSupply.add(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); emit Issuance(_amount); emit 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] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, this, _amount); emit 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 13 of 14: BancorGasPriceLimit
pragma solidity ^0.4.18; 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; } } 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; } 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); } } contract IBancorGasPriceLimit { function gasPrice() public view returns (uint256) {} function validateGasPrice(uint256) public view; } 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) { 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 14 of 14: BancorFormula
// File: contracts/converter/interfaces/IBancorFormula.sol pragma solidity 0.4.26; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256); // deprecated, backward compatibility function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() 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)); _; } } // File: contracts/converter/BancorFormula.sol pragma solidity 0.4.26; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; uint16 public version = 6; uint256 private constant ONE = 1; uint32 private constant MAX_RATIO = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** * Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** * Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** * Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** * Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // 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] = 0x00857ddf0117efa215952912839f6473e6; } /** * @dev given a token supply, reserve balance, ratio and a deposit amount (in the reserve token), * calculates the return for a given conversion (in the main token) * * Formula: * Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 1000000) - 1) * * @param _supply token total supply * @param _reserveBalance total reserve balance * @param _reserveRatio 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 view returns (uint256) { // validate input require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the ratio = 100% if (_reserveRatio == MAX_RATIO) return _supply.mul(_depositAmount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_reserveBalance); (result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_RATIO); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a token supply, reserve balance, ratio and a sell amount (in the main token), * calculates the return for a given conversion (in the reserve token) * * Formula: * Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1000000 / _reserveRatio)) * * @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 view returns (uint256) { // validate input require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO && _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 ratio = 100% if (_reserveRatio == MAX_RATIO) return _reserveBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_RATIO, _reserveRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given two reserve balances/ratios and a sell amount (in the first reserve token), * calculates the return for a conversion from the first reserve token to the second reserve token (in the second reserve token) * note that prior to version 4, you should use 'calculateCrossConnectorReturn' instead * * Formula: * Return = _toReserveBalance * (1 - (_fromReserveBalance / (_fromReserveBalance + _amount)) ^ (_fromReserveRatio / _toReserveRatio)) * * @param _fromReserveBalance input reserve balance * @param _fromReserveRatio input reserve ratio, represented in ppm, 1-1000000 * @param _toReserveBalance output reserve balance * @param _toReserveRatio output reserve ratio, represented in ppm, 1-1000000 * @param _amount input reserve amount * * @return second reserve amount */ function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256) { // validate input require(_fromReserveBalance > 0 && _fromReserveRatio > 0 && _fromReserveRatio <= MAX_RATIO && _toReserveBalance > 0 && _toReserveRatio > 0 && _toReserveRatio <= MAX_RATIO); // special case for equal ratios if (_fromReserveRatio == _toReserveRatio) return _toReserveBalance.mul(_amount) / _fromReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromReserveBalance.add(_amount); (result, precision) = power(baseN, _fromReserveBalance, _fromReserveRatio, _toReserveRatio); uint256 temp1 = _toReserveBalance.mul(result); uint256 temp2 = _toReserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given a smart token supply, reserve balance, total ratio and an amount of requested smart tokens, * calculates the amount of reserve tokens required for purchasing the given amount of smart tokens * * Formula: * Return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_RATIO / _totalRatio) - 1) * * @param _supply smart token supply * @param _reserveBalance reserve token balance * @param _totalRatio total ratio, represented in ppm, 2-2000000 * @param _amount requested amount of smart tokens * * @return amount of reserve tokens */ function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256) { // validate input require(_supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2); // special case for 0 amount if (_amount == 0) return 0; // special case if the total ratio = 100% if (_totalRatio == MAX_RATIO) return (_amount.mul(_reserveBalance) - 1) / _supply + 1; uint256 result; uint8 precision; uint256 baseN = _supply.add(_amount); (result, precision) = power(baseN, _supply, MAX_RATIO, _totalRatio); uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1; return temp - _reserveBalance; } /** * @dev given a smart token supply, reserve balance, total ratio and an amount of smart tokens to liquidate, * calculates the amount of reserve tokens received for selling the given amount of smart tokens * * Formula: * Return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_RATIO / _totalRatio)) * * @param _supply smart token supply * @param _reserveBalance reserve token balance * @param _totalRatio total ratio, represented in ppm, 2-2000000 * @param _amount amount of smart tokens to liquidate * * @return amount of reserve tokens */ function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256) { // validate input require(_supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2 && _amount <= _supply); // special case for 0 amount if (_amount == 0) return 0; // special case for liquidating the entire supply if (_amount == _supply) return _reserveBalance; // special case if the total ratio = 100% if (_totalRatio == MAX_RATIO) return _amount.mul(_reserveBalance) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_RATIO, _totalRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev 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 ^ (log(base) * exp)". * The value of "log(base)" is represented with an integer slightly smaller than "log(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. * This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". * Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** * @dev computes log(x / FIXED_1) * FIXED_1. * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // 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_NUMERATOR / LN2_DENOMINATOR; } /** * @dev computes the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure 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; } /** * @dev 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 view 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; require(false); return 0; } /** * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". * it returns "e ^ (x / 2 ^ precision) * 2 ^ 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 generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** * @dev computes log(x / FIXED_1) * FIXED_1 * Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 * Auto-generated via 'PrintFunctionOptimalLog.py' * Detailed description: * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 * - The natural logarithm of the input is calculated by summing up the intermediate results above * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } /** * @dev deprecated, backward compatibility */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { return calculateCrossReserveReturn(_fromConnectorBalance, _fromConnectorWeight, _toConnectorBalance, _toConnectorWeight, _amount); } }