Transaction Hash:
Block:
9058556 at Dec-06-2019 04:12:48 AM +UTC
Transaction Fee:
0.0022917184 ETH
$5.56
Gas Used:
92,408 Gas / 24.8 Gwei
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x04668Ec2...D451c8F7F
Miner
| (zhizhu.top) | 846.166662192887191891 Eth | 846.168953911287191891 Eth | 0.0022917184 | |
0x96e50cCD...8671C8E1B |
28.903626185293080843 Eth
Nonce: 3956
|
28.901334466893080843 Eth
Nonce: 3957
| 0.0022917184 |
Execution Trace
BancorConverter.b3a426d5( )
-
ContractRegistry.getAddress( _contractName=42616E636F724E6574776F726B00000000000000000000000000000000000000 ) => ( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a )
-
EtherToken.transferFrom( _from=0x96e50cCD13EBF0791D4d8F1caC0c66B8671C8E1B, _to=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _value=0 ) => ( success=True )
BancorNetwork.convertForPrioritized2( _path=[0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xd7eB9DB184DA9f099B84e2F86b1da1Fe6b305B3d, 0x6810e776880C02933D47DB1b9fc05908e5386b96], _amount=0, _minReturn=1, _for=0x96e50cCD13EBF0791D4d8F1caC0c66B8671C8E1B, _block=0, _v=0, _r=0000000000000000000000000000000000000000000000000000000000000000, _s=0000000000000000000000000000000000000000000000000000000000000000 )
-
ContractRegistry.addressOf( _contractName=436F6E7472616374466561747572657300000000000000000000000000000000 ) => ( 0x563172281800B139f69fB038cC2C08CaD56Ce699 )
-
SmartToken.CALL( )
-
ContractFeatures.isSupported( _contract=0x9c248517b92Ae226B88a0a0C28dE02B9B7b039D3, _features=1 ) => ( True )
-
BancorConverter.CALL( )
-
SmartToken.CALL( )
-
ContractFeatures.isSupported( _contract=0x3f7Ba8B8F663fdDB47568CCA30eac7aeD3D2F1A3, _features=1 ) => ( True )
-
BancorConverter.CALL( )
-
ContractRegistry.addressOf( _contractName=42616E636F7247617350726963654C696D697400000000000000000000000000 ) => ( 0x607a5C47978e2Eb6d59C6C6f51bc0bF411f4b85a )
-
BancorGasPriceLimit.validateGasPrice( _gasPrice=24800000000 )
-
File 1 of 10: BancorConverter
File 2 of 10: ContractRegistry
File 3 of 10: EtherToken
File 4 of 10: BancorNetwork
File 5 of 10: ContractRegistry
File 6 of 10: SmartToken
File 7 of 10: ContractFeatures
File 8 of 10: BancorConverter
File 9 of 10: SmartToken
File 10 of 10: BancorGasPriceLimit
pragma solidity ^0.4.21; /* 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; } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /* 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; } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /* Bancor Network interface */ contract IBancorNetwork { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); 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); } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /* 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; event ManagerUpdate(address indexed _prevManager, address indexed _newManager); /** @dev constructor */ function Managed() public { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } // 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); } } /** 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"; // 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_FACTORY = "BancorConverterFactory"; bytes32 public constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader"; // tokens bytes32 public constant BNT_TOKEN = "BNTToken"; } /** 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; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() public { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* The smart token controller is an upgradable part of the smart token that allows more functionality as well as fixes for bugs/exploits. Once it accepts ownership of the token, it becomes the token's sole controller that can execute any of its functions. To upgrade the controller, ownership must be transferred to a new controller, along with any relevant data. The smart token must be set on construction and cannot be changed afterwards. Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access. Note that the controller can transfer token ownership to a new controller that doesn't allow executing any function on the token, for a trustless solution. Doing that will also remove the owner's ability to upgrade the controller. */ contract SmartTokenController is TokenHolder { ISmartToken public token; // smart token /** @dev constructor */ function SmartTokenController(ISmartToken _token) public validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { assert(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { assert(token.owner() != address(this)); _; } /** @dev allows transferring the token ownership the new owner still need to accept the transfer can only be called by the contract owner @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly { token.transferOwnership(_newOwner); } /** @dev used by a new owner to accept a token ownership transfer can only be called by the contract owner */ function acceptTokenOwnership() public ownerOnly { token.acceptOwnership(); } /** @dev disables/enables token transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTokenTransfers(bool _disable) public ownerOnly { token.disableTransfers(_disable); } /** @dev withdraws tokens held by the controller and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawFromToken( IERC20Token _token, address _to, uint256 _amount ) public ownerOnly { ITokenHolder(token).withdrawTokens(_token, _to, _amount); } } /* Bancor Converter v0.9 The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves. ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract. The converter is upgradable (just like any SmartTokenController). WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits or with very small numbers because of precision loss Open issues: - Front-running attacks are currently mitigated by the following mechanisms: - minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction - gas price limit prevents users from having control over the order of execution - 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 connector fields so that the client won't need to rely on the order in the struct */ contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractIds, FeatureIds { uint32 private constant MAX_WEIGHT = 1000000; uint64 private constant MAX_CONVERSION_FEE = 1000000; struct Connector { uint256 virtualBalance; // connector virtual balance uint32 weight; // connector weight, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner bool isSet; // used to tell if the mapping element is defined } string public version = '0.9'; string public converterType = 'bancor'; IContractRegistry public registry; // contract registry contract IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public connectorTokens; // ERC20 standard token addresses IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH mapping (address => Connector) public connectors; // connector token addresses -> connector data uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100% uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, // represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%) uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee bool public conversionsEnabled = true; // true if token conversions is enabled, false if not IERC20Token[] private convertPath; // triggered when a conversion between two tokens occurs event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); // triggered after a conversion with new price data event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); // triggered when the conversion fee is updated event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** @dev constructor @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 _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector */ function BancorConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public SmartTokenController(_token) validAddress(_registry) validMaxConversionFee(_maxConversionFee) { registry = _registry; IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); // initialize supported features if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_connectorToken != address(0)) addConnector(_connectorToken, _connectorWeight, false); } // validates a connector token address - verifies that the address belongs to one of the connector tokens modifier validConnector(IERC20Token _address) { require(connectors[_address].isSet); _; } // validates a token address - verifies that the address belongs to one of the convertible tokens modifier validToken(IERC20Token _address) { require(_address == token || connectors[_address].isSet); _; } // validates maximum conversion fee modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); _; } // validates connector weight range modifier validConnectorWeight(uint32 _weight) { require(_weight > 0 && _weight <= MAX_WEIGHT); _; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { assert(conversionsEnabled); _; } // allows execution by the BancorNetwork contract only modifier bancorNetworkOnly { IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); require(msg.sender == address(bancorNetwork)); _; } /** @dev returns the number of connector tokens defined @return number of connector tokens */ function connectorTokenCount() public view returns (uint16) { return uint16(connectorTokens.length); } /* @dev allows the owner to update the registry contract address @param _registry address of a bancor converter registry contract */ function setRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @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 allows the manager to update the quick buy path @param _path new quick buy path, see conversion path format in the bancorNetwork contract */ function setQuickBuyPath(IERC20Token[] _path) public ownerOnly validConversionPath(_path) { quickBuyPath = _path; } /* @dev allows the manager to clear the quick buy path */ function clearQuickBuyPath() public ownerOnly { quickBuyPath.length = 0; } /** @dev returns the length of the quick buy path array @return quick buy path length */ function getQuickBuyPathLength() public view returns (uint256) { return quickBuyPath.length; } /** @dev disables the entire conversion functionality this is a safety mechanism in case of a emergency can only be called by the manager @param _disable true to disable conversions, false to re-enable them */ function disableConversions(bool _disable) public ownerOrManagerOnly { conversionsEnabled = !_disable; } /** @dev updates the current conversion fee can only be called by the manager @param _conversionFee new conversion fee, represented in ppm */ function setConversionFee(uint32 _conversionFee) public ownerOrManagerOnly validConversionFee(_conversionFee) { 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 connector conversion @return return amount minus conversion fee */ function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) { return safeMul(_amount, (MAX_CONVERSION_FEE - conversionFee) ** _magnitude) / MAX_CONVERSION_FEE ** _magnitude; } /** @dev defines a new connector for the token can only be called by the owner while the converter is inactive @param _token address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it */ function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validConnectorWeight(_weight) { require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input connectors[_token].virtualBalance = 0; connectors[_token].weight = _weight; connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance; connectors[_token].isPurchaseEnabled = true; connectors[_token].isSet = true; connectorTokens.push(_token); totalConnectorWeight += _weight; } /** @dev updates one of the token connectors can only be called by the owner @param _connectorToken address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it @param _virtualBalance new connector's virtual balance */ function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validConnector(_connectorToken) validConnectorWeight(_weight) { Connector storage connector = connectors[_connectorToken]; require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input totalConnectorWeight = totalConnectorWeight - connector.weight + _weight; connector.weight = _weight; connector.isVirtualBalanceEnabled = _enableVirtualBalance; connector.virtualBalance = _virtualBalance; } /** @dev disables purchasing with the given connector token in case the connector token got compromised can only be called by the owner note that selling is still enabled regardless of this flag and it cannot be disabled by the owner @param _connectorToken connector token contract address @param _disable true to disable the token, false to re-enable it */ function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable) public ownerOnly validConnector(_connectorToken) { connectors[_connectorToken].isPurchaseEnabled = !_disable; } /** @dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance @param _connectorToken connector token contract address @return connector balance */ function getConnectorBalance(IERC20Token _connectorToken) public view validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this); } /** @dev returns the expected return for converting a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @return expected conversion return amount */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // conversion between 2 connectors return getCrossConnectorReturn(_fromToken, _toToken, _amount); } /** @dev returns the expected return for buying the token for a connector token @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @return expected purchase return amount */ function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; require(connector.isPurchaseEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling the token for one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @return expected sale return amount */ function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling one of the connector tokens for another connector token @param _fromConnectorToken contract address of the connector token to convert from @param _toConnectorToken contract address of the connector token to convert to @param _sellAmount amount to sell (in the from connector token) @return expected sale return amount (in the to connector token) */ function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount) public view active validConnector(_fromConnectorToken) validConnector(_toConnectorToken) returns (uint256) { Connector storage fromConnector = connectors[_fromConnectorToken]; Connector storage toConnector = connectors[_toConnectorToken]; require(toConnector.isPurchaseEnabled); // validate input uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken); uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount); // return the amount minus the conversion fee // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) return getFinalAmount(amount, 2); } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public bancorNetworkOnly conversionsAllowed greaterThanZero(_minReturn) returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); // conversion between 2 connectors uint256 amount = getCrossConnectorReturn(_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 Connector storage fromConnector = connectors[_fromToken]; if (fromConnector.isVirtualBalanceEnabled) fromConnector.virtualBalance = safeAdd(fromConnector.virtualBalance, _amount); // update the target token virtual balance if relevant Connector storage toConnector = connectors[_toToken]; if (toConnector.isVirtualBalanceEnabled) toConnector.virtualBalance = safeSub(toConnector.virtualBalance, amount); // ensure that the trade won't deplete the connector balance uint256 toConnectorBalance = getConnectorBalance(_toToken); assert(amount < toConnectorBalance); // transfer funds from the caller in the from connector token assert(_fromToken.transferFrom(msg.sender, this, _amount)); // transfer funds to the caller in the to connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_toToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 2)); dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount); // dispatch price data updates for the smart token / both connectors emit PriceDataUpdate(_fromToken, token.totalSupply(), getConnectorBalance(_fromToken), fromConnector.weight); emit PriceDataUpdate(_toToken, token.totalSupply(), getConnectorBalance(_toToken), toConnector.weight); return amount; } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { convertPath = [_fromToken, token, _toToken]; return quickConvert(convertPath, _amount, _minReturn); } /** @dev buys the token by depositing one of its connector tokens @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return buy return amount */ function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) { uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount); // transfer funds from the caller in the connector token assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount)); // issue new funds to the caller in the smart token token.issue(msg.sender, amount); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev sells the token by withdrawing from one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero @return sell return amount */ function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input uint256 amount = getSaleReturn(_connectorToken, _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 connector balance if the total supply is depleted as well uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply)); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeSub(connector.virtualBalance, amount); // destroy _sellAmount from the caller's balance in the smart token token.destroy(msg.sender, _sellAmount); // transfer funds to the caller in the connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_connectorToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(token, _connectorToken, _sellAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the 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 @return tokens issued in return */ function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable validConversionPath(_path) returns (uint256) { return quickConvertPrioritized(_path, _amount, _minReturn, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the 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 _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps validating if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps validating if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps validating if the signature is legit @return tokens issued in return */ function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { IERC20Token fromToken = _path[0]; IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.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 (fromToken == 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 assert(fromToken.transferFrom(msg.sender, bancorNetwork, _amount)); } } // execute the conversion and pass on the ETH with the call return bancorNetwork.convertForPrioritized2.value(msg.value)(_path, _amount, _minReturn, msg.sender, _block, _v, _r, _s); } // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertInternal(_fromToken, _toToken, _amount, _minReturn); } /** @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)); } /** @dev fallback, buys the smart token with ETH note that the purchase will use the price at the time of the purchase */ function() payable public { quickConvert(quickBuyPath, msg.value, 1); } }
File 2 of 10: ContractRegistry
pragma solidity ^0.4.21; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /** 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 strings to optimize gas costs */ contract ContractRegistry is IContractRegistry, Owned { mapping (bytes32 => address) addresses; event AddressUpdate(bytes32 indexed _contractName, address _contractAddress); /** @dev constructor */ function ContractRegistry() public { } /** @dev returns the address associated with the given contract name @param _contractName contract name @return contract address */ function getAddress(bytes32 _contractName) public view returns (address) { return addresses[_contractName]; } /** @dev registers a new address for the contract name @param _contractName contract name @param _contractAddress contract address */ function registerAddress(bytes32 _contractName, address _contractAddress) public ownerOnly { require(_contractName.length > 0); // validating input addresses[_contractName] = _contractAddress; emit AddressUpdate(_contractName, _contractAddress); } }
File 3 of 10: EtherToken
pragma solidity ^0.4.11; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public constant returns (address owner) { owner; } function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); /** @dev constructor */ function Owned() { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string name) { name; } function symbol() public constant returns (string symbol) { symbol; } function decimals() public constant returns (uint8 decimals) { decimals; } function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; } function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /** ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { string public standard = 'Token 0.1'; string public name = ''; string public symbol = ''; uint8 public decimals = 0; uint256 public totalSupply = 0; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** @dev constructor @param _name token name @param _symbol token symbol @param _decimals decimal points, for display purposes */ function ERC20Token(string _name, string _symbol, uint8 _decimals) { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; } /** @dev send coins throws on any error rather then return a false flag to minimize user errors @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) { allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } /** @dev allow another account/contract to spend some tokens on your behalf throws on any error rather then return a false flag to minimize user errors also, to minimize the risk of the approve/transferFrom attack vector (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value @param _spender approved address @param _value allowance amount @return true if the approval was successful, false if it wasn't */ function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } /* Ether Token interface */ contract IEtherToken is ITokenHolder, IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function withdrawTo(address _to, uint256 _amount); } /** Ether tokenization contract 'Owned' is specified here for readability reasons */ contract EtherToken is IEtherToken, Owned, ERC20Token, TokenHolder { // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); /** @dev constructor */ function EtherToken() ERC20Token('Ether Token', 'ETH', 18) { } /** @dev deposit ether in the account */ function deposit() public payable { balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], msg.value); // add the value to the account balance totalSupply = safeAdd(totalSupply, msg.value); // increase the total supply Issuance(msg.value); Transfer(this, msg.sender, msg.value); } /** @dev withdraw ether from the account @param _amount amount of ether to withdraw */ function withdraw(uint256 _amount) public { withdrawTo(msg.sender, _amount); } /** @dev withdraw ether from the account to a target account @param _to account to receive the ether @param _amount amount of ether to withdraw */ function withdrawTo(address _to, uint256 _amount) public notThis(_to) { balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount); // deduct the amount from the account balance totalSupply = safeSub(totalSupply, _amount); // decrease the total supply _to.transfer(_amount); // send the amount to the target account Transfer(msg.sender, this, _amount); Destruction(_amount); } // ERC20 standard method overrides with some extra protection /** @dev send coins throws on any error rather then return a false flag to minimize user errors @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public notThis(_to) returns (bool success) { assert(super.transfer(_to, _value)); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public notThis(_to) returns (bool success) { assert(super.transferFrom(_from, _to, _value)); return true; } /** @dev deposit ether in the account */ function() public payable { deposit(); } }
File 4 of 10: BancorNetwork
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) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } // File: contracts/IBancorNetwork.sol /* 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/ContractIds.sol /** * @dev 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"; bytes32 public constant NON_STANDARD_TOKEN_REGISTRY = "NonStandardTokenRegistry"; // 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"; // BNT core bytes32 public constant BNT_TOKEN = "BNTToken"; bytes32 public constant BNT_CONVERTER = "BNTConverter"; // BancorX bytes32 public constant BANCOR_X = "BancorX"; bytes32 public constant BANCOR_X_UPGRADER = "BancorXUpgrader"; } // File: contracts/FeatureIds.sol /** * @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 /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } // File: contracts/converter/interfaces/IBancorConverter.sol /* 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) {} function conversionFee() public view returns (uint32) {} function reserves(address _address) public view returns (uint256, uint32, bool, bool, bool) { _address; } function getReserveBalance(IERC20Token _reserveToken) public view returns (uint256); // 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); } // File: contracts/converter/interfaces/IBancorFormula.sol /* 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); // 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 /* Bancor Gas Price Limit interface */ contract IBancorGasPriceLimit { function gasPrice() public view returns (uint256) {} function validateGasPrice(uint256) public view; } // 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 /** * @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 /** * @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 /* 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) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public; 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/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/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/utility/interfaces/IContractFeatures.sol /* 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 /* Address list interface */ contract IAddressList { mapping (address => bool) public listedAddresses; } // File: contracts/token/interfaces/IEtherToken.sol /* 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 /* 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 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 /** * @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, ContractIds, 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 IContractRegistry public registry; // contract registry contract address 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 initializes a new BancorNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public validAddress(_registry) { registry = _registry; } /** * @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 contract registry contract address * * @param _registry address of a contract registry contract */ function setRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /** * @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 trusted by recovering * the address associated with the public key from elliptic * curve signature, returns zero on error. * notice that the signature is valid only for one conversion * and 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 converter should already own the source tokens * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from (in the initial source token) * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _for account that will receive the conversion result * @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 converter should already own the source tokens * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from (in the initial source token) * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _for account that will receive the conversion result * @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 ensureTransfer(toToken, _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 * * @return the amount of BNT received from this conversion */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId ) public payable returns (uint256) { return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(0x0, 0x0, 0x0, 0x0, 0x0)); } /** * @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 * * @return the amount of BNT received from this conversion */ function xConvertPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _toBlockchain, bytes32 _to, uint256 _conversionId, uint256[] memory _signature ) 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] == registry.addressOf(ContractIds.BNT_TOKEN)); // handle msg.value handleValue(_path[0], _amount, true); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, address(0), 0); // transfer the resulting amount to BancorX IBancorX(registry.addressOf(ContractIds.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 amount = _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 = registry.addressOf(ContractIds.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, amount); // make the conversion - if it's the last one, also provide the minimum return value amount = converter.change(_path[i - 2], _path[i], amount, i == lastIndex ? _minReturn : 1); // pay affiliate-fee if needed if (address(_path[i]) == bntToken) { uint256 affiliateAmount = amount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(_path[i].transfer(_affiliateAccount, affiliateAmount)); amount -= affiliateAmount; bntToken = address(0); } } return amount; } 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 returns the expected return amount for converting a specific amount by following * a given conversion path. * notice that there is no support for circular paths. * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from (in the initial source token) * * @return expected conversion return amount and conversion 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(registry.addressOf(ContractIds.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()); } // validate input require(getReserveSaleEnabled(converter, fromToken)); // 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 converter before we follow // the conversion path, to allow it to execute the conversion on behalf of the caller // note: we assume we already have allowance IERC20Token fromToken = _path[0]; 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 converter should already own the source tokens * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from (in the initial source token) * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _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 _to the address to transfer the tokens to * @param _amount the amount to transfer */ function ensureTransfer(IERC20Token _token, address _to, uint256 _amount) private { IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY)); if (addressList.listedAddresses(_token)) { uint256 prevBalance = _token.balanceOf(_to); // we have to cast the token contract in an interface which has no return value INonStandardERC20(_token).transfer(_to, _amount); uint256 postBalance = _token.balanceOf(_to); assert(postBalance > prevBalance); } else { // if the token isn't whitelisted, we assert on transfer assert(_token.transfer(_to, _amount)); } } /** * @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 { IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY)); if (addressList.listedAddresses(_token)) { uint256 prevBalance = _token.balanceOf(_to); // we have to cast the token contract in an interface which has no return value INonStandardERC20(_token).transferFrom(_from, _to, _amount); uint256 postBalance = _token.balanceOf(_to); assert(postBalance > prevBalance); } else { // if the token isn't whitelisted, we assert on transfer assert(_token.transferFrom(_from, _to, _amount)); } } /** * @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 { // check if allowance for the given amount already exists if (_token.allowance(this, _spender) >= _value) return; // if the allowance is nonzero, must reset it to 0 first if (_token.allowance(this, _spender) != 0) INonStandardERC20(_token).approve(_spender, 0); // approve the new allowance INonStandardERC20(_token).approve(_spender, _value); } /** * @dev returns true if reserve sale is enabled * * @param _converter converter contract address * @param _reserve reserve's address to read from * * @return true if reserve sale is enabled, otherwise - false */ function getReserveSaleEnabled(IBancorConverter _converter, IERC20Token _reserve) private view returns(bool) { bool isSaleEnabled; (, , , isSaleEnabled, ) = _converter.connectors(_reserve); return isSaleEnabled; } 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(registry.addressOf(ContractIds.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(registry.addressOf(ContractIds.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 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 xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, signature); // return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(_amount, _block, _v, _r, _s)); } /** * @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 5 of 10: 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 6 of 10: SmartToken
pragma solidity ^0.4.11; /* Overflow protected math functions */ contract SafeMath { /** constructor */ function SafeMath() { } /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public constant returns (address owner) { owner; } function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); /** @dev constructor */ function Owned() { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still need to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned { /** @dev constructor */ function TokenHolder() { } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string name) { name; } function symbol() public constant returns (string symbol) { symbol; } function decimals() public constant returns (uint8 decimals) { decimals; } function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; } function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /** ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, SafeMath { string public standard = 'Token 0.1'; string public name = ''; string public symbol = ''; uint8 public decimals = 0; uint256 public totalSupply = 0; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** @dev constructor @param _name token name @param _symbol token symbol @param _decimals decimal points, for display purposes */ function ERC20Token(string _name, string _symbol, uint8 _decimals) { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } /** @dev send coins throws on any error rather then return a false flag to minimize user errors @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) { allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } /** @dev allow another account/contract to spend some tokens on your behalf throws on any error rather then return a false flag to minimize user errors also, to minimize the risk of the approve/transferFrom attack vector (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value @param _spender approved address @param _value allowance amount @return true if the approval was successful, false if it wasn't */ function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } /* Smart Token interface */ contract ISmartToken is ITokenHolder, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /* Smart Token v0.2 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, ERC20Token, Owned, TokenHolder { string public version = '0.2'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory event NewSmartToken(address _token); // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); /** @dev constructor @param _name token name @param _symbol token short symbol, 1-6 characters @param _decimals for display purposes only */ function SmartToken(string _name, string _symbol, uint8 _decimals) ERC20Token(_name, _symbol, _decimals) { require(bytes(_symbol).length <= 6); // validate input NewSmartToken(address(this)); } // allows execution only when transfers aren't disabled modifier transfersAllowed { assert(transfersEnabled); _; } /** @dev disables/enables transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } /** @dev increases the token supply and sends the new tokens to an account can only be called by the contract owner @param _to account to receive the new amount @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = safeAdd(totalSupply, _amount); balanceOf[_to] = safeAdd(balanceOf[_to], _amount); Issuance(_amount); Transfer(this, _to, _amount); } /** @dev removes tokens from an account and decreases the token supply can only be called by the contract owner @param _from account to remove the amount from @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public ownerOnly { balanceOf[_from] = safeSub(balanceOf[_from], _amount); totalSupply = safeSub(totalSupply, _amount); Transfer(_from, this, _amount); Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** @dev send coins throws on any error rather then return a false flag to minimize user errors note that when transferring to the smart token's address, the coins are actually destroyed @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); // transferring to the contract address destroys tokens if (_to == address(this)) { balanceOf[_to] -= _value; totalSupply -= _value; Destruction(_value); } return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors note that when transferring to the smart token's address, the coins are actually destroyed @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); // transferring to the contract address destroys tokens if (_to == address(this)) { balanceOf[_to] -= _value; totalSupply -= _value; Destruction(_value); } return true; } }
File 7 of 10: 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 8 of 10: BancorConverter
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/interfaces/IWhitelist.sol /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } // File: contracts/converter/interfaces/IBancorConverter.sol /* 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); } // File: contracts/converter/interfaces/IBancorConverterUpgrader.sol /* Bancor Converter Upgrader interface */ contract IBancorConverterUpgrader { function upgrade(bytes32 _version) public; function upgrade(uint16 _version) public; } // File: contracts/converter/interfaces/IBancorFormula.sol /* 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); // deprecated, backward compatibility function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: contracts/IBancorNetwork.sol /* 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/ContractIds.sol /** * @dev 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"; bytes32 public constant NON_STANDARD_TOKEN_REGISTRY = "NonStandardTokenRegistry"; // 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"; // BNT core bytes32 public constant BNT_TOKEN = "BNTToken"; bytes32 public constant BNT_CONVERTER = "BNTConverter"; // BancorX bytes32 public constant BANCOR_X = "BancorX"; bytes32 public constant BANCOR_X_UPGRADER = "BancorXUpgrader"; } // File: contracts/FeatureIds.sol /** * @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 /* 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 /** * @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 /** * @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/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/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/utility/interfaces/IContractFeatures.sol /* 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 /* Address list interface */ contract IAddressList { mapping (address => bool) public listedAddresses; } // 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/token/interfaces/ISmartTokenController.sol /* 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 /* 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/SmartTokenController.sol /** * @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 /* 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 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 /** * @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 the calculations are based on the virtual balance instead of relying on the actual reserve balance. * * This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract. * * The converter is upgradable (just like any SmartTokenController) 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, ContractIds, 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 = 19; string public converterType = 'bancor'; bool public allowRegistryUpdate = true; // allows the owner to prevent/allow the registry to be updated IContractRegistry public prevRegistry; // address of previous registry as security mechanism IContractRegistry public registry; // contract registry contract 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 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 ) public SmartTokenController(_token) validAddress(_registry) validConversionFee(_maxConversionFee) { registry = _registry; prevRegistry = _registry; IContractFeatures features = IContractFeatures(registry.addressOf(ContractIds.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, false); } // 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 the total ratio is 100% modifier fullTotalRatioOnly() { require(totalReserveRatio == RATIO_RESOLUTION); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { require(conversionsEnabled); _; } // allows execution by the BancorNetwork contract only modifier bancorNetworkOnly { IBancorNetwork bancorNetwork = IBancorNetwork(registry.addressOf(ContractIds.BANCOR_NETWORK)); require(msg.sender == address(bancorNetwork)); _; } // allows execution by the converter upgrader contract only modifier converterUpgraderOnly { address converterUpgrader = registry.addressOf(ContractIds.BANCOR_CONVERTER_UPGRADER); require(owner == converterUpgrader); _; } // allows execution only if the total-supply of the token is greater than zero modifier totalSupplyGreaterThanZeroOnly { require(token.totalSupply() > 0); _; } /** * @dev sets the contract registry to whichever address the current registry is pointing to */ function updateRegistry() public { // require that upgrading is allowed or that the caller is the owner require(allowRegistryUpdate || msg.sender == owner); // get the address of whichever registry the current registry is pointing to address newRegistry = registry.addressOf(ContractIds.CONTRACT_REGISTRY); // if the new registry hasn't changed or is the zero address, revert require(newRegistry != address(registry) && newRegistry != address(0)); // set the previous registry as current registry and current registry as newRegistry prevRegistry = registry; registry = IContractRegistry(newRegistry); } /** * @dev security mechanism allowing the converter owner to revert to the previous registry, * to be used in emergency scenario */ function restoreRegistry() public ownerOrManagerOnly { // set the registry as previous registry registry = prevRegistry; // after a previous registry is restored, only the owner can allow future updates allowRegistryUpdate = false; } /** * @dev disables the registry update functionality * this is a safety mechanism in case of a emergency * can only be called by the manager or owner * * @param _disable true to disable registry updates, false to re-enable them */ function disableRegistryUpdate(bool _disable) public ownerOrManagerOnly { allowRegistryUpdate = !_disable; } /** * @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 converterUpgraderOnly { 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 = registry.addressOf(ContractIds.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(registry.addressOf(ContractIds.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 * @param _enableVirtualBalance true to enable virtual balance for the reserve, false to disable it */ function addReserve(IERC20Token _token, uint32 _ratio, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validReserveRatio(_ratio) { require(_token != token && !reserves[_token].isSet && totalReserveRatio + _ratio <= RATIO_RESOLUTION); // validate input reserves[_token].virtualBalance = 0; reserves[_token].ratio = _ratio; reserves[_token].isVirtualBalanceEnabled = _enableVirtualBalance; reserves[_token].isSaleEnabled = true; reserves[_token].isSet = true; reserveTokens.push(_token); totalReserveRatio += _ratio; } /** * @dev updates one of the token reserves * can only be called by the owner * note that prior to version 17, you should use 'updateConnector' instead * * @param _reserveToken address of the reserve token * @param _ratio constant reserve ratio, represented in ppm, 1-1000000 * @param _enableVirtualBalance true to enable virtual balance for the reserve, false to disable it * @param _virtualBalance new reserve's virtual balance */ function updateReserve(IERC20Token _reserveToken, uint32 _ratio, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validReserve(_reserveToken) validReserveRatio(_ratio) { Reserve storage reserve = reserves[_reserveToken]; require(totalReserveRatio - reserve.ratio + _ratio <= RATIO_RESOLUTION); // validate input totalReserveRatio = totalReserveRatio - reserve.ratio + _ratio; reserve.ratio = _ratio; reserve.isVirtualBalanceEnabled = _enableVirtualBalance; reserve.virtualBalance = _virtualBalance; } /** * @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 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 = getReserveBalance(_reserveToken); IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.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 = getReserveBalance(_reserveToken); IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.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(registry.addressOf(ContractIds.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 bancorNetworkOnly 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 the actual reserve balance is smaller than the virtual balance ensureTransfer(_toToken, 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(), getReserveBalance(_fromToken), fromReserve.ratio); emit PriceDataUpdate(_toToken, token.totalSupply(), getReserveBalance(_toToken), 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(), getReserveBalance(_reserveToken), 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 = getReserveBalance(_reserveToken); 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 // the transfer might fail if the actual reserve balance is smaller than the virtual balance ensureTransfer(_reserveToken, 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(), getReserveBalance(_reserveToken), 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(registry.addressOf(ContractIds.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(registry.addressOf(ContractIds.BANCOR_X)); IBancorNetwork bancorNetwork = IBancorNetwork(registry.addressOf(ContractIds.BANCOR_NETWORK)); // verify that the first token in the path is BNT require(_path[0] == registry.addressOf(ContractIds.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 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 _to the address to transfer the tokens to * @param _amount the amount to transfer */ function ensureTransfer(IERC20Token _token, address _to, uint256 _amount) private { IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY)); if (addressList.listedAddresses(_token)) { uint256 prevBalance = _token.balanceOf(_to); // we have to cast the token contract in an interface which has no return value INonStandardERC20(_token).transfer(_to, _amount); uint256 postBalance = _token.balanceOf(_to); assert(postBalance > prevBalance); } else { // if the token isn't whitelisted, we assert on transfer assert(_token.transfer(_to, _amount)); } } /** * @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 { IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY)); if (addressList.listedAddresses(_token)) { uint256 prevBalance = _token.balanceOf(_to); // we have to cast the token contract in an interface which has no return value INonStandardERC20(_token).transferFrom(_from, _to, _amount); uint256 postBalance = _token.balanceOf(_to); assert(postBalance > prevBalance); } else { // if the token is standard, we assert on transfer assert(_token.transferFrom(_from, _to, _amount)); } } /** * @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 if the total ratio is 100% and conversions are enabled * * @param _amount amount to increase the supply by (in the smart token) */ function fund(uint256 _amount) public fullTotalRatioOnly conversionsAllowed { uint256 supply = token.totalSupply(); // 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 = getReserveBalance(reserveToken); reserveAmount = _amount.mul(reserveBalance).sub(1).div(supply).add(1); // 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 only if the total ratio is 100% * * @param _amount amount to liquidate (in the smart token) */ function liquidate(uint256 _amount) public fullTotalRatioOnly { uint256 supply = token.totalSupply(); // 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 = getReserveBalance(reserveToken); reserveAmount = _amount.mul(reserveBalance).div(supply); // 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 // the transfer might fail if the actual reserve balance is smaller than the virtual balance ensureTransfer(reserveToken, 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, _enableVirtualBalance); } /** * @dev deprecated, backward compatibility */ function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance) public { updateReserve(_connectorToken, _weight, _enableVirtualBalance, _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 9 of 10: SmartToken
pragma solidity ^0.4.11; // File: contracts/Utils.sol /* 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; } } // File: contracts/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 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); } // File: contracts/ERC20Token.sol /** 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; } } // File: contracts/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 constant returns (address owner) { owner; } function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/Owned.sol /* 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; } } // File: contracts/interfaces/ITokenHolder.sol /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/TokenHolder.sol /* 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)); } } // File: contracts/interfaces/ISmartToken.sol /* 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; } // File: contracts\SmartToken.sol /* Smart Token v0.3 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder { string public version = '0.3'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory event NewSmartToken(address _token); // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); /** @dev constructor @param _name token name @param _symbol token short symbol, minimum 1 character @param _decimals for display purposes only */ function SmartToken(string _name, string _symbol, uint8 _decimals) ERC20Token(_name, _symbol, _decimals) { NewSmartToken(address(this)); } // allows execution only when transfers aren't disabled modifier transfersAllowed { assert(transfersEnabled); _; } /** @dev disables/enables transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } /** @dev increases the token supply and sends the new tokens to an account can only be called by the contract owner @param _to account to receive the new amount @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = safeAdd(totalSupply, _amount); balanceOf[_to] = safeAdd(balanceOf[_to], _amount); Issuance(_amount); Transfer(this, _to, _amount); } /** @dev removes tokens from an account and decreases the token supply can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account @param _from account to remove the amount from @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public { require(msg.sender == _from || msg.sender == owner); // validate input balanceOf[_from] = safeSub(balanceOf[_from], _amount); totalSupply = safeSub(totalSupply, _amount); Transfer(_from, this, _amount); Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** @dev send coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); return true; } }
File 10 of 10: 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); } }