contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
Skraps
Skraps.sol
0xfdfe8b7ab6cf1bd1e3d14538ef40686296c42052
Solidity
Crowdsale
contract Crowdsale is AdvancedToken { uint internal endOfFreeze = 1522569600; // Sun, 01 Apr 2018 00:00:00 PST uint private tokensForSalePhase2; uint public tokensPerEther; address internal reserve = 0x4B046B05C29E535E152A3D9c8FB7540a8e15c7A6; function Crowdsale() internal { assert(reserve != address(0)); tokensPerEther = 2000 * 1 ether; // Tokens ^ 18 totalSupply = MAX_SUPPLY; uint MARKET_SHARE = 66000000 * 1 ether; uint tokensSoldPhase1 = 11110257 * 1 ether; tokensForSalePhase2 = MARKET_SHARE - tokensSoldPhase1; // Tokens for the Phase 2 are on the contract and not available to withdraw by owner during the ICO balances[address(this)] = tokensForSalePhase2; // Tokens for the Phase 1 are on the owner to distribution by manually processes balances[owner] = totalSupply - tokensForSalePhase2; assert(balances[address(this)] + balances[owner] == MAX_SUPPLY); Transfer(0, address(this), balances[address(this)]); Transfer(0, owner, balances[owner]); } // Setting the number of tokens to buy for 1 Ether, changes automatically by owner or support account function setTokensPerEther(uint _tokens) public supportOrOwner { require(state == State.ICO || state == State.Waiting); require(_tokens > 100 ether); // Min 100 tokens ^ 18 tokensPerEther = _tokens; } // The payable function to buy Skraps tokens function () internal payable { require(msg.sender != address(0)); require(state == State.ICO || state == State.Migration); if (state == State.ICO) { // The minimum ether to participate require(msg.value >= 0.01 ether); // Counting and sending tokens to the investor uint _tokens = msg.value * tokensPerEther / 1 ether; require(balances[address(this)] >= _tokens); balances[address(this)] = balances[address(this)].sub(_tokens); balances[msg.sender] = balances[msg.sender].add(_tokens); Transfer(address(this), msg.sender, _tokens); // send 25% of ether received to reserve address uint to_reserve = msg.value * 25 / 100; reserve.transfer(to_reserve); } else { require(msg.value == 0); migrate(); } } // Start ISO manually because the block timestamp is not mean the current time function startICO() public supportOrOwner { require(state == State.Waiting); state = State.ICO; NewState(state); } // Since a contracts can not call itself, we must manually close the ICO function closeICO() public onlyOwner { require(state == State.ICO); state = State.Running; NewState(state); } // Anti-scam function, if the tokens are obtained by dishonest means, can be used only during ICO function refundTokens(address _from, uint _value) public onlyOwner { require(state == State.ICO); require(balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[address(this)] = balances[address(this)].add(_value); Transfer(_from, address(this), _value); } }
closeICO
function closeICO() public onlyOwner { require(state == State.ICO); state = State.Running; NewState(state); }
// Since a contracts can not call itself, we must manually close the ICO
LineComment
v0.4.20+commit.3155dd80
bzzr://b8ece78acfc7f5a80fe3a6dc139e5772225c589ca46f007597d561ab2ab3e5e4
{ "func_code_index": [ 2757, 2903 ] }
57,961
Skraps
Skraps.sol
0xfdfe8b7ab6cf1bd1e3d14538ef40686296c42052
Solidity
Crowdsale
contract Crowdsale is AdvancedToken { uint internal endOfFreeze = 1522569600; // Sun, 01 Apr 2018 00:00:00 PST uint private tokensForSalePhase2; uint public tokensPerEther; address internal reserve = 0x4B046B05C29E535E152A3D9c8FB7540a8e15c7A6; function Crowdsale() internal { assert(reserve != address(0)); tokensPerEther = 2000 * 1 ether; // Tokens ^ 18 totalSupply = MAX_SUPPLY; uint MARKET_SHARE = 66000000 * 1 ether; uint tokensSoldPhase1 = 11110257 * 1 ether; tokensForSalePhase2 = MARKET_SHARE - tokensSoldPhase1; // Tokens for the Phase 2 are on the contract and not available to withdraw by owner during the ICO balances[address(this)] = tokensForSalePhase2; // Tokens for the Phase 1 are on the owner to distribution by manually processes balances[owner] = totalSupply - tokensForSalePhase2; assert(balances[address(this)] + balances[owner] == MAX_SUPPLY); Transfer(0, address(this), balances[address(this)]); Transfer(0, owner, balances[owner]); } // Setting the number of tokens to buy for 1 Ether, changes automatically by owner or support account function setTokensPerEther(uint _tokens) public supportOrOwner { require(state == State.ICO || state == State.Waiting); require(_tokens > 100 ether); // Min 100 tokens ^ 18 tokensPerEther = _tokens; } // The payable function to buy Skraps tokens function () internal payable { require(msg.sender != address(0)); require(state == State.ICO || state == State.Migration); if (state == State.ICO) { // The minimum ether to participate require(msg.value >= 0.01 ether); // Counting and sending tokens to the investor uint _tokens = msg.value * tokensPerEther / 1 ether; require(balances[address(this)] >= _tokens); balances[address(this)] = balances[address(this)].sub(_tokens); balances[msg.sender] = balances[msg.sender].add(_tokens); Transfer(address(this), msg.sender, _tokens); // send 25% of ether received to reserve address uint to_reserve = msg.value * 25 / 100; reserve.transfer(to_reserve); } else { require(msg.value == 0); migrate(); } } // Start ISO manually because the block timestamp is not mean the current time function startICO() public supportOrOwner { require(state == State.Waiting); state = State.ICO; NewState(state); } // Since a contracts can not call itself, we must manually close the ICO function closeICO() public onlyOwner { require(state == State.ICO); state = State.Running; NewState(state); } // Anti-scam function, if the tokens are obtained by dishonest means, can be used only during ICO function refundTokens(address _from, uint _value) public onlyOwner { require(state == State.ICO); require(balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[address(this)] = balances[address(this)].add(_value); Transfer(_from, address(this), _value); } }
refundTokens
function refundTokens(address _from, uint _value) public onlyOwner { require(state == State.ICO); require(balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[address(this)] = balances[address(this)].add(_value); Transfer(_from, address(this), _value); }
// Anti-scam function, if the tokens are obtained by dishonest means, can be used only during ICO
LineComment
v0.4.20+commit.3155dd80
bzzr://b8ece78acfc7f5a80fe3a6dc139e5772225c589ca46f007597d561ab2ab3e5e4
{ "func_code_index": [ 3009, 3349 ] }
57,962
MetaZooGames
contracts/MetaZooGames.sol
0x2d366be8fa4d15c289964dd4adf7be6cc5e896e8
Solidity
MetaZooGames
contract MetaZooGames is ERC721Enumerable, Ownable { using Strings for uint256; uint256 public sales_end; modifier onlyAllowed() { require( permitted[msg.sender] || (msg.sender == owner()), "Unauthorised" ); _; } constructor(uint256 _sales_start) ERC721("MetaZoo Games Tokens", "MZGT") { sales_end = _sales_start + 12 hours; } mapping(address => bool) public permitted; bool public saleLock = true; string public localBaseURL = "https://metazoo-metadata-server.herokuapp.com/api/metadata/"; function _baseURI() internal view override returns (string memory) { return localBaseURL; } function setDataFolder(string memory __baseURI) public onlyOwner { localBaseURL = __baseURI; } function lockStatus() public view returns (bool) { return (sales_end >= block.timestamp || totalSupply() == 5000); } function endSales() public onlyOwner { // To trigger when sales over. sales_end = block.timestamp; } function contractURI() public view returns (string memory) { // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI(), "contract.json")); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); // reformat to directory structure as below string memory file = tokenId.toString(); return string(abi.encodePacked(_baseURI(), file)); } // https://metazoo-metadata-server.herokuapp.com/api/metadata/<id> function setAllowed(address _addr, bool _state) external onlyOwner { permitted[_addr] = _state; } function mintCards(uint256 numberOfCards, address recipient) external onlyAllowed { // check the max is 5k. uint256 currentCount = totalSupply(); require(currentCount + numberOfCards <= 5000, "Max supply"); for (uint256 i = 1; i <= numberOfCards; i++) { _mint(recipient, currentCount + i); } } function retrieveETH() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } function retrieveERC20(address _tracker, uint256 amount) external onlyOwner { IERC20(_tracker).transfer(msg.sender, amount); } function retrieve721(address _tracker, uint256 id) external onlyOwner { IERC721(_tracker).transferFrom(address(this), msg.sender, id); } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal override { if (lockStatus()) { // if lock , cannot transfer. if (_from == address(0)) { // Do transfer Sales part, ERC721Enumerable._beforeTokenTransfer(_from, _to, _tokenId); } else { revert("saleLock"); } } else { // normal after sales. ERC721Enumerable._beforeTokenTransfer(_from, _to, _tokenId); } } }
//// @author: Blockchain platform powered by Ether Cards - https://ether.cards
NatSpecSingleLine
setAllowed
function setAllowed(address _addr, bool _state) external onlyOwner { permitted[_addr] = _state; }
// https://metazoo-metadata-server.herokuapp.com/api/metadata/<id>
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 1790, 1903 ] }
57,963
StrategyStEth
contracts/strategies/StrategyStEth.sol
0x2cf1ab3a110ed495e38df9b5f67ee2381c7bb572
Solidity
StrategyStEth
contract StrategyStEth is StrategyETH { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant SUSHI = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve // // liquidity provider token (Curve ETH/STETH) address private constant LP = 0x06325440D014e39736583c165C2963BA99fAf14E; // StableSwapSTETH address private constant POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LiquidityGaugeV2 address private constant GAUGE = 0x182B723a58739a9c974cFDB385ceaDb237453c28; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; // LIDO // address private constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; address private constant LDO = 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32; constructor(address _controller, address _vault) public StrategyETH(_controller, _vault) { // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(SUSHI, uint(-1)); // Minted on Gauge deposit, withdraw and claim_rewards // only this contract can spend on SUSHI IERC20(LDO).safeApprove(SUSHI, uint(-1)); } receive() external payable { // Don't allow vault to accidentally send ETH require(msg.sender != vault, "msg.sender = vault"); } function _totalAssets() internal view override returns (uint) { uint shares = LiquidityGaugeV2(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); return shares.mul(pricePerShare) / 1e18; } function _getStEthDepositAmount(uint _ethBal) private view returns (uint) { /* Goal is to find a0 and a1 such that b0 + a0 is close to b1 + a1 E = amount of ETH b0 = balance of ETH in Curve b1 = balance of stETH in Curve a0 = amount of ETH to deposit into Curve a1 = amount of stETH to deposit into Curve d = |b0 - b1| if d >= E if b0 >= b1 a0 = 0 a1 = E else a0 = E a1 = 0 else if b0 >= b1 # add d to balance Curve pool, plus half of remaining a1 = d + (E - d) / 2 = (E + d) / 2 a0 = E - a1 else a0 = (E + d) / 2 a1 = E - a0 */ uint[2] memory balances; balances[0] = StableSwapSTETH(POOL).balances(0); balances[1] = StableSwapSTETH(POOL).balances(1); uint diff; if (balances[0] >= balances[1]) { diff = balances[0] - balances[1]; } else { diff = balances[1] - balances[0]; } // a0 = ETH amount is ignored, recomputed after stEth is bought // a1 = stETH amount uint a1; if (diff >= _ethBal) { if (balances[0] >= balances[1]) { a1 = _ethBal; } } else { if (balances[0] >= balances[1]) { a1 = (_ethBal.add(diff)) / 2; } else { a1 = _ethBal.sub((_ethBal.add(diff)) / 2); } } // a0 is ignored, recomputed after stEth is bought return a1; } /* @notice Deposits ETH to LiquidityGaugeV2 */ function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { StETH(ST_ETH).submit{value: stEthAmount}(address(this)); } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { // ST_ETH is proxy so don't allow infinite approval IERC20(ST_ETH).safeApprove(POOL, stEthBal); } /* shares = eth amount * 1e18 / price per share */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min); } // stake into LiquidityGaugeV2 uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } } function _getTotalShares() internal view override returns (uint) { return LiquidityGaugeV2(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGaugeV2 LiquidityGaugeV2(GAUGE).withdraw(_lpAmount); uint lpBal = IERC20(LP).balanceOf(address(this)); /* eth amount = (shares * price per shares) / 1e18 */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint ethAmount = lpBal.mul(pricePerShare) / 1e18; uint min = ethAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).remove_liquidity_one_coin(lpBal, 0, min); // Now we have ETH } /* @dev SUSHI fails with zero address so no check is necessary here */ function _swapToEth(address _from, uint _amount) private { // create dynamic array with 2 elements address[] memory path = new address[](2); path[0] = _from; path[1] = WETH; Uniswap(SUSHI).swapExactTokensForETH( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards() private { // claim LDO LiquidityGaugeV2(GAUGE).claim_rewards(); // claim CRV Minter(MINTER).mint(GAUGE); // Infinity approval for SUSHI set inside constructor uint ldoBal = IERC20(LDO).balanceOf(address(this)); if (ldoBal > 0) { _swapToEth(LDO, ldoBal); } uint crvBal = IERC20(CRV).balanceOf(address(this)); if (crvBal > 0) { _swapToEth(CRV, crvBal); } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { _claimRewards(); uint bal = address(this).balance; if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); // treasury must be able to receive ETH (bool sent, ) = treasury.call{value: fee}(""); require(sent, "Send ETH failed"); } _deposit(); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != GAUGE, "protected token"); require(_token != LDO, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
_deposit
function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { StETH(ST_ETH).submit{value: stEthAmount}(address(this)); } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { // ST_ETH is proxy so don't allow infinite approval IERC20(ST_ETH).safeApprove(POOL, stEthBal); } /* shares = eth amount * 1e18 / price per share */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min); } // stake into LiquidityGaugeV2 uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } }
/* @notice Deposits ETH to LiquidityGaugeV2 */
Comment
v0.6.11+commit.5ef660b1
Unknown
ipfs://b6ba645a470307459caa5d8c87e70ea0efd7f2cce82473b17587258c4c8803be
{ "func_code_index": [ 3739, 4996 ] }
57,964
StrategyStEth
contracts/strategies/StrategyStEth.sol
0x2cf1ab3a110ed495e38df9b5f67ee2381c7bb572
Solidity
StrategyStEth
contract StrategyStEth is StrategyETH { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant SUSHI = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve // // liquidity provider token (Curve ETH/STETH) address private constant LP = 0x06325440D014e39736583c165C2963BA99fAf14E; // StableSwapSTETH address private constant POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LiquidityGaugeV2 address private constant GAUGE = 0x182B723a58739a9c974cFDB385ceaDb237453c28; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; // LIDO // address private constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; address private constant LDO = 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32; constructor(address _controller, address _vault) public StrategyETH(_controller, _vault) { // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(SUSHI, uint(-1)); // Minted on Gauge deposit, withdraw and claim_rewards // only this contract can spend on SUSHI IERC20(LDO).safeApprove(SUSHI, uint(-1)); } receive() external payable { // Don't allow vault to accidentally send ETH require(msg.sender != vault, "msg.sender = vault"); } function _totalAssets() internal view override returns (uint) { uint shares = LiquidityGaugeV2(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); return shares.mul(pricePerShare) / 1e18; } function _getStEthDepositAmount(uint _ethBal) private view returns (uint) { /* Goal is to find a0 and a1 such that b0 + a0 is close to b1 + a1 E = amount of ETH b0 = balance of ETH in Curve b1 = balance of stETH in Curve a0 = amount of ETH to deposit into Curve a1 = amount of stETH to deposit into Curve d = |b0 - b1| if d >= E if b0 >= b1 a0 = 0 a1 = E else a0 = E a1 = 0 else if b0 >= b1 # add d to balance Curve pool, plus half of remaining a1 = d + (E - d) / 2 = (E + d) / 2 a0 = E - a1 else a0 = (E + d) / 2 a1 = E - a0 */ uint[2] memory balances; balances[0] = StableSwapSTETH(POOL).balances(0); balances[1] = StableSwapSTETH(POOL).balances(1); uint diff; if (balances[0] >= balances[1]) { diff = balances[0] - balances[1]; } else { diff = balances[1] - balances[0]; } // a0 = ETH amount is ignored, recomputed after stEth is bought // a1 = stETH amount uint a1; if (diff >= _ethBal) { if (balances[0] >= balances[1]) { a1 = _ethBal; } } else { if (balances[0] >= balances[1]) { a1 = (_ethBal.add(diff)) / 2; } else { a1 = _ethBal.sub((_ethBal.add(diff)) / 2); } } // a0 is ignored, recomputed after stEth is bought return a1; } /* @notice Deposits ETH to LiquidityGaugeV2 */ function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { StETH(ST_ETH).submit{value: stEthAmount}(address(this)); } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { // ST_ETH is proxy so don't allow infinite approval IERC20(ST_ETH).safeApprove(POOL, stEthBal); } /* shares = eth amount * 1e18 / price per share */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min); } // stake into LiquidityGaugeV2 uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } } function _getTotalShares() internal view override returns (uint) { return LiquidityGaugeV2(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGaugeV2 LiquidityGaugeV2(GAUGE).withdraw(_lpAmount); uint lpBal = IERC20(LP).balanceOf(address(this)); /* eth amount = (shares * price per shares) / 1e18 */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint ethAmount = lpBal.mul(pricePerShare) / 1e18; uint min = ethAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).remove_liquidity_one_coin(lpBal, 0, min); // Now we have ETH } /* @dev SUSHI fails with zero address so no check is necessary here */ function _swapToEth(address _from, uint _amount) private { // create dynamic array with 2 elements address[] memory path = new address[](2); path[0] = _from; path[1] = WETH; Uniswap(SUSHI).swapExactTokensForETH( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards() private { // claim LDO LiquidityGaugeV2(GAUGE).claim_rewards(); // claim CRV Minter(MINTER).mint(GAUGE); // Infinity approval for SUSHI set inside constructor uint ldoBal = IERC20(LDO).balanceOf(address(this)); if (ldoBal > 0) { _swapToEth(LDO, ldoBal); } uint crvBal = IERC20(CRV).balanceOf(address(this)); if (crvBal > 0) { _swapToEth(CRV, crvBal); } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { _claimRewards(); uint bal = address(this).balance; if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); // treasury must be able to receive ETH (bool sent, ) = treasury.call{value: fee}(""); require(sent, "Send ETH failed"); } _deposit(); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != GAUGE, "protected token"); require(_token != LDO, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
_swapToEth
function _swapToEth(address _from, uint _amount) private { // create dynamic array with 2 elements address[] memory path = new address[](2); path[0] = _from; path[1] = WETH; Uniswap(SUSHI).swapExactTokensForETH( _amount, 1, path, address(this), block.timestamp ); }
/* @dev SUSHI fails with zero address so no check is necessary here */
Comment
v0.6.11+commit.5ef660b1
Unknown
ipfs://b6ba645a470307459caa5d8c87e70ea0efd7f2cce82473b17587258c4c8803be
{ "func_code_index": [ 5854, 6250 ] }
57,965
StrategyStEth
contracts/strategies/StrategyStEth.sol
0x2cf1ab3a110ed495e38df9b5f67ee2381c7bb572
Solidity
StrategyStEth
contract StrategyStEth is StrategyETH { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant SUSHI = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve // // liquidity provider token (Curve ETH/STETH) address private constant LP = 0x06325440D014e39736583c165C2963BA99fAf14E; // StableSwapSTETH address private constant POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LiquidityGaugeV2 address private constant GAUGE = 0x182B723a58739a9c974cFDB385ceaDb237453c28; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; // LIDO // address private constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; address private constant LDO = 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32; constructor(address _controller, address _vault) public StrategyETH(_controller, _vault) { // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(SUSHI, uint(-1)); // Minted on Gauge deposit, withdraw and claim_rewards // only this contract can spend on SUSHI IERC20(LDO).safeApprove(SUSHI, uint(-1)); } receive() external payable { // Don't allow vault to accidentally send ETH require(msg.sender != vault, "msg.sender = vault"); } function _totalAssets() internal view override returns (uint) { uint shares = LiquidityGaugeV2(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); return shares.mul(pricePerShare) / 1e18; } function _getStEthDepositAmount(uint _ethBal) private view returns (uint) { /* Goal is to find a0 and a1 such that b0 + a0 is close to b1 + a1 E = amount of ETH b0 = balance of ETH in Curve b1 = balance of stETH in Curve a0 = amount of ETH to deposit into Curve a1 = amount of stETH to deposit into Curve d = |b0 - b1| if d >= E if b0 >= b1 a0 = 0 a1 = E else a0 = E a1 = 0 else if b0 >= b1 # add d to balance Curve pool, plus half of remaining a1 = d + (E - d) / 2 = (E + d) / 2 a0 = E - a1 else a0 = (E + d) / 2 a1 = E - a0 */ uint[2] memory balances; balances[0] = StableSwapSTETH(POOL).balances(0); balances[1] = StableSwapSTETH(POOL).balances(1); uint diff; if (balances[0] >= balances[1]) { diff = balances[0] - balances[1]; } else { diff = balances[1] - balances[0]; } // a0 = ETH amount is ignored, recomputed after stEth is bought // a1 = stETH amount uint a1; if (diff >= _ethBal) { if (balances[0] >= balances[1]) { a1 = _ethBal; } } else { if (balances[0] >= balances[1]) { a1 = (_ethBal.add(diff)) / 2; } else { a1 = _ethBal.sub((_ethBal.add(diff)) / 2); } } // a0 is ignored, recomputed after stEth is bought return a1; } /* @notice Deposits ETH to LiquidityGaugeV2 */ function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { StETH(ST_ETH).submit{value: stEthAmount}(address(this)); } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { // ST_ETH is proxy so don't allow infinite approval IERC20(ST_ETH).safeApprove(POOL, stEthBal); } /* shares = eth amount * 1e18 / price per share */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min); } // stake into LiquidityGaugeV2 uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } } function _getTotalShares() internal view override returns (uint) { return LiquidityGaugeV2(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGaugeV2 LiquidityGaugeV2(GAUGE).withdraw(_lpAmount); uint lpBal = IERC20(LP).balanceOf(address(this)); /* eth amount = (shares * price per shares) / 1e18 */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint ethAmount = lpBal.mul(pricePerShare) / 1e18; uint min = ethAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).remove_liquidity_one_coin(lpBal, 0, min); // Now we have ETH } /* @dev SUSHI fails with zero address so no check is necessary here */ function _swapToEth(address _from, uint _amount) private { // create dynamic array with 2 elements address[] memory path = new address[](2); path[0] = _from; path[1] = WETH; Uniswap(SUSHI).swapExactTokensForETH( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards() private { // claim LDO LiquidityGaugeV2(GAUGE).claim_rewards(); // claim CRV Minter(MINTER).mint(GAUGE); // Infinity approval for SUSHI set inside constructor uint ldoBal = IERC20(LDO).balanceOf(address(this)); if (ldoBal > 0) { _swapToEth(LDO, ldoBal); } uint crvBal = IERC20(CRV).balanceOf(address(this)); if (crvBal > 0) { _swapToEth(CRV, crvBal); } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { _claimRewards(); uint bal = address(this).balance; if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); // treasury must be able to receive ETH (bool sent, ) = treasury.call{value: fee}(""); require(sent, "Send ETH failed"); } _deposit(); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != GAUGE, "protected token"); require(_token != LDO, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
harvest
function harvest() external override onlyAuthorized { _claimRewards(); uint bal = address(this).balance; if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); // treasury must be able to receive ETH (bool sent, ) = treasury.call{value: fee}(""); require(sent, "Send ETH failed"); } _deposit(); } }
/* @notice Claim CRV and deposit most premium token into Curve */
Comment
v0.6.11+commit.5ef660b1
Unknown
ipfs://b6ba645a470307459caa5d8c87e70ea0efd7f2cce82473b17587258c4c8803be
{ "func_code_index": [ 6855, 7527 ] }
57,966
StrategyStEth
contracts/strategies/StrategyStEth.sol
0x2cf1ab3a110ed495e38df9b5f67ee2381c7bb572
Solidity
StrategyStEth
contract StrategyStEth is StrategyETH { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant SUSHI = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve // // liquidity provider token (Curve ETH/STETH) address private constant LP = 0x06325440D014e39736583c165C2963BA99fAf14E; // StableSwapSTETH address private constant POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LiquidityGaugeV2 address private constant GAUGE = 0x182B723a58739a9c974cFDB385ceaDb237453c28; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; // LIDO // address private constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; address private constant LDO = 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32; constructor(address _controller, address _vault) public StrategyETH(_controller, _vault) { // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(SUSHI, uint(-1)); // Minted on Gauge deposit, withdraw and claim_rewards // only this contract can spend on SUSHI IERC20(LDO).safeApprove(SUSHI, uint(-1)); } receive() external payable { // Don't allow vault to accidentally send ETH require(msg.sender != vault, "msg.sender = vault"); } function _totalAssets() internal view override returns (uint) { uint shares = LiquidityGaugeV2(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); return shares.mul(pricePerShare) / 1e18; } function _getStEthDepositAmount(uint _ethBal) private view returns (uint) { /* Goal is to find a0 and a1 such that b0 + a0 is close to b1 + a1 E = amount of ETH b0 = balance of ETH in Curve b1 = balance of stETH in Curve a0 = amount of ETH to deposit into Curve a1 = amount of stETH to deposit into Curve d = |b0 - b1| if d >= E if b0 >= b1 a0 = 0 a1 = E else a0 = E a1 = 0 else if b0 >= b1 # add d to balance Curve pool, plus half of remaining a1 = d + (E - d) / 2 = (E + d) / 2 a0 = E - a1 else a0 = (E + d) / 2 a1 = E - a0 */ uint[2] memory balances; balances[0] = StableSwapSTETH(POOL).balances(0); balances[1] = StableSwapSTETH(POOL).balances(1); uint diff; if (balances[0] >= balances[1]) { diff = balances[0] - balances[1]; } else { diff = balances[1] - balances[0]; } // a0 = ETH amount is ignored, recomputed after stEth is bought // a1 = stETH amount uint a1; if (diff >= _ethBal) { if (balances[0] >= balances[1]) { a1 = _ethBal; } } else { if (balances[0] >= balances[1]) { a1 = (_ethBal.add(diff)) / 2; } else { a1 = _ethBal.sub((_ethBal.add(diff)) / 2); } } // a0 is ignored, recomputed after stEth is bought return a1; } /* @notice Deposits ETH to LiquidityGaugeV2 */ function _deposit() internal override { uint bal = address(this).balance; if (bal > 0) { uint stEthAmount = _getStEthDepositAmount(bal); if (stEthAmount > 0) { StETH(ST_ETH).submit{value: stEthAmount}(address(this)); } uint ethBal = address(this).balance; uint stEthBal = IERC20(ST_ETH).balanceOf(address(this)); if (stEthBal > 0) { // ST_ETH is proxy so don't allow infinite approval IERC20(ST_ETH).safeApprove(POOL, stEthBal); } /* shares = eth amount * 1e18 / price per share */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint shares = bal.mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).add_liquidity{value: ethBal}([ethBal, stEthBal], min); } // stake into LiquidityGaugeV2 uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGaugeV2(GAUGE).deposit(lpBal); } } function _getTotalShares() internal view override returns (uint) { return LiquidityGaugeV2(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGaugeV2 LiquidityGaugeV2(GAUGE).withdraw(_lpAmount); uint lpBal = IERC20(LP).balanceOf(address(this)); /* eth amount = (shares * price per shares) / 1e18 */ uint pricePerShare = StableSwapSTETH(POOL).get_virtual_price(); uint ethAmount = lpBal.mul(pricePerShare) / 1e18; uint min = ethAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; StableSwapSTETH(POOL).remove_liquidity_one_coin(lpBal, 0, min); // Now we have ETH } /* @dev SUSHI fails with zero address so no check is necessary here */ function _swapToEth(address _from, uint _amount) private { // create dynamic array with 2 elements address[] memory path = new address[](2); path[0] = _from; path[1] = WETH; Uniswap(SUSHI).swapExactTokensForETH( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards() private { // claim LDO LiquidityGaugeV2(GAUGE).claim_rewards(); // claim CRV Minter(MINTER).mint(GAUGE); // Infinity approval for SUSHI set inside constructor uint ldoBal = IERC20(LDO).balanceOf(address(this)); if (ldoBal > 0) { _swapToEth(LDO, ldoBal); } uint crvBal = IERC20(CRV).balanceOf(address(this)); if (crvBal > 0) { _swapToEth(CRV, crvBal); } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { _claimRewards(); uint bal = address(this).balance; if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); // treasury must be able to receive ETH (bool sent, ) = treasury.call{value: fee}(""); require(sent, "Send ETH failed"); } _deposit(); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != GAUGE, "protected token"); require(_token != LDO, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
exit
function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); }
/* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */
Comment
v0.6.11+commit.5ef660b1
Unknown
ipfs://b6ba645a470307459caa5d8c87e70ea0efd7f2cce82473b17587258c4c8803be
{ "func_code_index": [ 7777, 7948 ] }
57,967
TutellusPartnerCrowdsale
contracts/TokenVesting.sol
0x65bcf8de5c59ee18a69733759c3b8040416c8fa2
Solidity
TokenVesting
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event KYCValid(address beneficiary); event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; // KYC valid bool public kycValid = false; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { require(kycValid); uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } function setValidKYC() onlyOwner public returns (bool) { kycValid = true; KYCValid(beneficiary); return true; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */
NatSpecMultiLine
TokenVesting
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; }
/** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */
NatSpecMultiLine
v0.4.15+commit.bbb8e64f
bzzr://f756ca5d67067c854166a83cf1ccb99adca0788bb88a0aab7e3b1d845ead5c4e
{ "func_code_index": [ 1099, 1449 ] }
57,968
TutellusPartnerCrowdsale
contracts/TokenVesting.sol
0x65bcf8de5c59ee18a69733759c3b8040416c8fa2
Solidity
TokenVesting
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event KYCValid(address beneficiary); event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; // KYC valid bool public kycValid = false; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { require(kycValid); uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } function setValidKYC() onlyOwner public returns (bool) { kycValid = true; KYCValid(beneficiary); return true; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */
NatSpecMultiLine
release
function release(ERC20Basic token) public { require(kycValid); uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); }
/** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */
NatSpecMultiLine
v0.4.15+commit.bbb8e64f
bzzr://f756ca5d67067c854166a83cf1ccb99adca0788bb88a0aab7e3b1d845ead5c4e
{ "func_code_index": [ 1573, 1870 ] }
57,969
TutellusPartnerCrowdsale
contracts/TokenVesting.sol
0x65bcf8de5c59ee18a69733759c3b8040416c8fa2
Solidity
TokenVesting
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event KYCValid(address beneficiary); event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; // KYC valid bool public kycValid = false; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { require(kycValid); uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } function setValidKYC() onlyOwner public returns (bool) { kycValid = true; KYCValid(beneficiary); return true; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */
NatSpecMultiLine
revoke
function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); }
/** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */
NatSpecMultiLine
v0.4.15+commit.bbb8e64f
bzzr://f756ca5d67067c854166a83cf1ccb99adca0788bb88a0aab7e3b1d845ead5c4e
{ "func_code_index": [ 2082, 2436 ] }
57,970
TutellusPartnerCrowdsale
contracts/TokenVesting.sol
0x65bcf8de5c59ee18a69733759c3b8040416c8fa2
Solidity
TokenVesting
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event KYCValid(address beneficiary); event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; // KYC valid bool public kycValid = false; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { require(kycValid); uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } function setValidKYC() onlyOwner public returns (bool) { kycValid = true; KYCValid(beneficiary); return true; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */
NatSpecMultiLine
releasableAmount
function releasableAmount(ERC20Basic token) public returns (uint256) { return vestedAmount(token).sub(released[token]); }
/** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */
NatSpecMultiLine
v0.4.15+commit.bbb8e64f
bzzr://f756ca5d67067c854166a83cf1ccb99adca0788bb88a0aab7e3b1d845ead5c4e
{ "func_code_index": [ 2593, 2725 ] }
57,971
TutellusPartnerCrowdsale
contracts/TokenVesting.sol
0x65bcf8de5c59ee18a69733759c3b8040416c8fa2
Solidity
TokenVesting
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event KYCValid(address beneficiary); event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; // KYC valid bool public kycValid = false; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { require(kycValid); uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } function setValidKYC() onlyOwner public returns (bool) { kycValid = true; KYCValid(beneficiary); return true; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */
NatSpecMultiLine
vestedAmount
function vestedAmount(ERC20Basic token) public returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } }
/** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */
NatSpecMultiLine
v0.4.15+commit.bbb8e64f
bzzr://f756ca5d67067c854166a83cf1ccb99adca0788bb88a0aab7e3b1d845ead5c4e
{ "func_code_index": [ 2853, 3263 ] }
57,972
HumansFactoryPass
/contracts/HumansFactoryPass.sol
0x5f6809f90b6ca15663b1fd791d548631df3664a8
Solidity
HumansFactoryPass
contract HumansFactoryPass is ERC1155Supply, Ownable, PaymentSplitter, ReentrancyGuard { using ECDSA for bytes32; using Strings for uint256; using Address for address payable; struct saleParams { string name; bool requireSignature; uint256 startTime; uint256 endTime; uint256 price; uint256 claimable; uint256 supply; uint256 tokenId; } address private signerAddress = 0xDC90586e77086E3A236ad5145df7B4bd7F628067; address[] private _team = [ 0xe2fe6d312138417Cdab7184D70D03B74f2Ce698C, 0xBf4fA1d9b2bAdBeA3373c637168191F07b317c17, 0x0b742B76A4C702262EcDd7DB75965c1754e8623a, 0x3433699934cd2485fa4fd78B04767F7e0075cb82, 0x99f794629E347ac97cb78457e1096dCfBB3b6498, 0xBAd8a212Ea950481871393147eA54c85be325e59, 0x002403988080d56798d2D30C4Ab498Da16bB38e2, 0xC89E9ecF1B2900656ECba77E1Da89600f187A50D, 0xa5bbE2Cd62e275d4Ecaa9a752783823308ACc4d0, 0x23C625789c391463997267BDD8b21e5E266014F6, 0x860Fd5caEb3306A1bcC2bca7d05F97439Df28574 ]; uint256[] private _teamShares = [2, 10, 10, 10, 10, 10, 2, 2, 2, 2, 40]; mapping(uint256 => saleParams) public sales; mapping(string => mapping(address => uint256)) public mintsPerWallet; mapping(string => uint256) public mintsPerSale; string public baseURI; bool public isPaused; string private name_; string private symbol_; event TokensMinted(address mintedBy, uint256 _nb, uint256 tokenId, string saleName); constructor(string memory _name, string memory _symbol) ERC1155("") PaymentSplitter(_team, _teamShares) { name_ = _name; symbol_ = _symbol; } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } // ADMIN function _setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setSignerAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "HF: You look into the deep space only to find nothing but emptiness."); signerAddress = _newAddress; } function withdrawAll() external onlyOwner { for (uint256 i = 0; i < _team.length; i++) { address payable wallet = payable(_team[i]); release(wallet); } } function pause(bool _isPaused) external onlyOwner { isPaused = _isPaused; } function configureSale( string memory _name, bool _requireSignature, uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _claimable, uint256 _supply, uint256 _tokenId, uint256 _id ) external onlyOwner { require(_startTime > 0 && _endTime > 0 && _endTime > _startTime, "HF: Time range is invalid."); sales[_id] = saleParams(_name, _requireSignature, _startTime, _endTime, _price, _claimable, _supply, _tokenId); } // MINT function airdrop( address _to, uint256 _nb, uint256 _tokenId ) external onlyOwner { require(totalSupply(_tokenId) + _nb <= maxSupplyOf(_tokenId), "HF: Not enough tokens left."); _mint(_to, _tokenId, _nb, ""); } function saleMint( uint256 _nb, uint256 _alloc, bytes calldata _signature, uint256 _saleId ) external payable nonReentrant { saleParams memory _sale = sales[_saleId]; require(_sale.startTime > 0 && _sale.endTime > 0, "HF: Sale doesn't exists"); // If a signature is required, the allocation is fetched from it // This allows a dynamic allocation per wallet uint256 alloc = _sale.requireSignature ? _alloc : _sale.claimable; if (_sale.requireSignature) { bytes32 _messageHash = hashMessage(abi.encode(_sale.name, address(this), _msgSender(), _alloc)); require(verifyAddressSigner(_messageHash, _signature), "HF: Invalid signature."); } require(_nb > 0, "HF: Wrong amount requested"); require(block.timestamp > _sale.startTime && block.timestamp < _sale.endTime, "HF: Sale is not active."); require(totalSupply(_sale.tokenId) + _nb <= maxSupplyOf(_sale.tokenId), "HF: Not enough tokens left."); require(mintsPerSale[_sale.name] + _nb <= _sale.supply, "HF: Not enough supply."); require(msg.value >= _nb * _sale.price, "HF: Insufficient amount."); require(mintsPerWallet[_sale.name][_msgSender()] + _nb <= alloc, "HF: Allocation exceeded."); mintsPerWallet[_sale.name][_msgSender()] += _nb; mintsPerSale[_sale.name] += _nb; _mint(_msgSender(), _sale.tokenId, _nb, ""); emit TokensMinted(_msgSender(), _nb, _sale.tokenId, _sale.name); } // PUBLIC function maxSupplyOf(uint256 _tokenId) public pure returns (uint256) { if (_tokenId == 0) return 333; else if (_tokenId == 1) return 3333; else return 0; } function uri(uint256 typeId) public view override returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, typeId.toString())) : baseURI; } // PRIVATE function verifyAddressSigner(bytes32 _messageHash, bytes memory _signature) private view returns (bool) { return signerAddress == _messageHash.toEthSignedMessageHash().recover(_signature); } function hashMessage(bytes memory _msg) private pure returns (bytes32) { return keccak256(_msg); } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!isPaused, "ERC1155Pausable: token transfer while paused"); } }
// @author: Array // dsc: Array#0007 // tw: @arraythedev // Contact me on twitter
LineComment
_setBaseURI
function _setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; }
// ADMIN
LineComment
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 1926, 2033 ] }
57,973
HumansFactoryPass
/contracts/HumansFactoryPass.sol
0x5f6809f90b6ca15663b1fd791d548631df3664a8
Solidity
HumansFactoryPass
contract HumansFactoryPass is ERC1155Supply, Ownable, PaymentSplitter, ReentrancyGuard { using ECDSA for bytes32; using Strings for uint256; using Address for address payable; struct saleParams { string name; bool requireSignature; uint256 startTime; uint256 endTime; uint256 price; uint256 claimable; uint256 supply; uint256 tokenId; } address private signerAddress = 0xDC90586e77086E3A236ad5145df7B4bd7F628067; address[] private _team = [ 0xe2fe6d312138417Cdab7184D70D03B74f2Ce698C, 0xBf4fA1d9b2bAdBeA3373c637168191F07b317c17, 0x0b742B76A4C702262EcDd7DB75965c1754e8623a, 0x3433699934cd2485fa4fd78B04767F7e0075cb82, 0x99f794629E347ac97cb78457e1096dCfBB3b6498, 0xBAd8a212Ea950481871393147eA54c85be325e59, 0x002403988080d56798d2D30C4Ab498Da16bB38e2, 0xC89E9ecF1B2900656ECba77E1Da89600f187A50D, 0xa5bbE2Cd62e275d4Ecaa9a752783823308ACc4d0, 0x23C625789c391463997267BDD8b21e5E266014F6, 0x860Fd5caEb3306A1bcC2bca7d05F97439Df28574 ]; uint256[] private _teamShares = [2, 10, 10, 10, 10, 10, 2, 2, 2, 2, 40]; mapping(uint256 => saleParams) public sales; mapping(string => mapping(address => uint256)) public mintsPerWallet; mapping(string => uint256) public mintsPerSale; string public baseURI; bool public isPaused; string private name_; string private symbol_; event TokensMinted(address mintedBy, uint256 _nb, uint256 tokenId, string saleName); constructor(string memory _name, string memory _symbol) ERC1155("") PaymentSplitter(_team, _teamShares) { name_ = _name; symbol_ = _symbol; } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } // ADMIN function _setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setSignerAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "HF: You look into the deep space only to find nothing but emptiness."); signerAddress = _newAddress; } function withdrawAll() external onlyOwner { for (uint256 i = 0; i < _team.length; i++) { address payable wallet = payable(_team[i]); release(wallet); } } function pause(bool _isPaused) external onlyOwner { isPaused = _isPaused; } function configureSale( string memory _name, bool _requireSignature, uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _claimable, uint256 _supply, uint256 _tokenId, uint256 _id ) external onlyOwner { require(_startTime > 0 && _endTime > 0 && _endTime > _startTime, "HF: Time range is invalid."); sales[_id] = saleParams(_name, _requireSignature, _startTime, _endTime, _price, _claimable, _supply, _tokenId); } // MINT function airdrop( address _to, uint256 _nb, uint256 _tokenId ) external onlyOwner { require(totalSupply(_tokenId) + _nb <= maxSupplyOf(_tokenId), "HF: Not enough tokens left."); _mint(_to, _tokenId, _nb, ""); } function saleMint( uint256 _nb, uint256 _alloc, bytes calldata _signature, uint256 _saleId ) external payable nonReentrant { saleParams memory _sale = sales[_saleId]; require(_sale.startTime > 0 && _sale.endTime > 0, "HF: Sale doesn't exists"); // If a signature is required, the allocation is fetched from it // This allows a dynamic allocation per wallet uint256 alloc = _sale.requireSignature ? _alloc : _sale.claimable; if (_sale.requireSignature) { bytes32 _messageHash = hashMessage(abi.encode(_sale.name, address(this), _msgSender(), _alloc)); require(verifyAddressSigner(_messageHash, _signature), "HF: Invalid signature."); } require(_nb > 0, "HF: Wrong amount requested"); require(block.timestamp > _sale.startTime && block.timestamp < _sale.endTime, "HF: Sale is not active."); require(totalSupply(_sale.tokenId) + _nb <= maxSupplyOf(_sale.tokenId), "HF: Not enough tokens left."); require(mintsPerSale[_sale.name] + _nb <= _sale.supply, "HF: Not enough supply."); require(msg.value >= _nb * _sale.price, "HF: Insufficient amount."); require(mintsPerWallet[_sale.name][_msgSender()] + _nb <= alloc, "HF: Allocation exceeded."); mintsPerWallet[_sale.name][_msgSender()] += _nb; mintsPerSale[_sale.name] += _nb; _mint(_msgSender(), _sale.tokenId, _nb, ""); emit TokensMinted(_msgSender(), _nb, _sale.tokenId, _sale.name); } // PUBLIC function maxSupplyOf(uint256 _tokenId) public pure returns (uint256) { if (_tokenId == 0) return 333; else if (_tokenId == 1) return 3333; else return 0; } function uri(uint256 typeId) public view override returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, typeId.toString())) : baseURI; } // PRIVATE function verifyAddressSigner(bytes32 _messageHash, bytes memory _signature) private view returns (bool) { return signerAddress == _messageHash.toEthSignedMessageHash().recover(_signature); } function hashMessage(bytes memory _msg) private pure returns (bytes32) { return keccak256(_msg); } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!isPaused, "ERC1155Pausable: token transfer while paused"); } }
// @author: Array // dsc: Array#0007 // tw: @arraythedev // Contact me on twitter
LineComment
airdrop
function airdrop( address _to, uint256 _nb, uint256 _tokenId ) external onlyOwner { require(totalSupply(_tokenId) + _nb <= maxSupplyOf(_tokenId), "HF: Not enough tokens left."); _mint(_to, _tokenId, _nb, ""); }
// MINT
LineComment
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 3099, 3361 ] }
57,974
HumansFactoryPass
/contracts/HumansFactoryPass.sol
0x5f6809f90b6ca15663b1fd791d548631df3664a8
Solidity
HumansFactoryPass
contract HumansFactoryPass is ERC1155Supply, Ownable, PaymentSplitter, ReentrancyGuard { using ECDSA for bytes32; using Strings for uint256; using Address for address payable; struct saleParams { string name; bool requireSignature; uint256 startTime; uint256 endTime; uint256 price; uint256 claimable; uint256 supply; uint256 tokenId; } address private signerAddress = 0xDC90586e77086E3A236ad5145df7B4bd7F628067; address[] private _team = [ 0xe2fe6d312138417Cdab7184D70D03B74f2Ce698C, 0xBf4fA1d9b2bAdBeA3373c637168191F07b317c17, 0x0b742B76A4C702262EcDd7DB75965c1754e8623a, 0x3433699934cd2485fa4fd78B04767F7e0075cb82, 0x99f794629E347ac97cb78457e1096dCfBB3b6498, 0xBAd8a212Ea950481871393147eA54c85be325e59, 0x002403988080d56798d2D30C4Ab498Da16bB38e2, 0xC89E9ecF1B2900656ECba77E1Da89600f187A50D, 0xa5bbE2Cd62e275d4Ecaa9a752783823308ACc4d0, 0x23C625789c391463997267BDD8b21e5E266014F6, 0x860Fd5caEb3306A1bcC2bca7d05F97439Df28574 ]; uint256[] private _teamShares = [2, 10, 10, 10, 10, 10, 2, 2, 2, 2, 40]; mapping(uint256 => saleParams) public sales; mapping(string => mapping(address => uint256)) public mintsPerWallet; mapping(string => uint256) public mintsPerSale; string public baseURI; bool public isPaused; string private name_; string private symbol_; event TokensMinted(address mintedBy, uint256 _nb, uint256 tokenId, string saleName); constructor(string memory _name, string memory _symbol) ERC1155("") PaymentSplitter(_team, _teamShares) { name_ = _name; symbol_ = _symbol; } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } // ADMIN function _setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setSignerAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "HF: You look into the deep space only to find nothing but emptiness."); signerAddress = _newAddress; } function withdrawAll() external onlyOwner { for (uint256 i = 0; i < _team.length; i++) { address payable wallet = payable(_team[i]); release(wallet); } } function pause(bool _isPaused) external onlyOwner { isPaused = _isPaused; } function configureSale( string memory _name, bool _requireSignature, uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _claimable, uint256 _supply, uint256 _tokenId, uint256 _id ) external onlyOwner { require(_startTime > 0 && _endTime > 0 && _endTime > _startTime, "HF: Time range is invalid."); sales[_id] = saleParams(_name, _requireSignature, _startTime, _endTime, _price, _claimable, _supply, _tokenId); } // MINT function airdrop( address _to, uint256 _nb, uint256 _tokenId ) external onlyOwner { require(totalSupply(_tokenId) + _nb <= maxSupplyOf(_tokenId), "HF: Not enough tokens left."); _mint(_to, _tokenId, _nb, ""); } function saleMint( uint256 _nb, uint256 _alloc, bytes calldata _signature, uint256 _saleId ) external payable nonReentrant { saleParams memory _sale = sales[_saleId]; require(_sale.startTime > 0 && _sale.endTime > 0, "HF: Sale doesn't exists"); // If a signature is required, the allocation is fetched from it // This allows a dynamic allocation per wallet uint256 alloc = _sale.requireSignature ? _alloc : _sale.claimable; if (_sale.requireSignature) { bytes32 _messageHash = hashMessage(abi.encode(_sale.name, address(this), _msgSender(), _alloc)); require(verifyAddressSigner(_messageHash, _signature), "HF: Invalid signature."); } require(_nb > 0, "HF: Wrong amount requested"); require(block.timestamp > _sale.startTime && block.timestamp < _sale.endTime, "HF: Sale is not active."); require(totalSupply(_sale.tokenId) + _nb <= maxSupplyOf(_sale.tokenId), "HF: Not enough tokens left."); require(mintsPerSale[_sale.name] + _nb <= _sale.supply, "HF: Not enough supply."); require(msg.value >= _nb * _sale.price, "HF: Insufficient amount."); require(mintsPerWallet[_sale.name][_msgSender()] + _nb <= alloc, "HF: Allocation exceeded."); mintsPerWallet[_sale.name][_msgSender()] += _nb; mintsPerSale[_sale.name] += _nb; _mint(_msgSender(), _sale.tokenId, _nb, ""); emit TokensMinted(_msgSender(), _nb, _sale.tokenId, _sale.name); } // PUBLIC function maxSupplyOf(uint256 _tokenId) public pure returns (uint256) { if (_tokenId == 0) return 333; else if (_tokenId == 1) return 3333; else return 0; } function uri(uint256 typeId) public view override returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, typeId.toString())) : baseURI; } // PRIVATE function verifyAddressSigner(bytes32 _messageHash, bytes memory _signature) private view returns (bool) { return signerAddress == _messageHash.toEthSignedMessageHash().recover(_signature); } function hashMessage(bytes memory _msg) private pure returns (bytes32) { return keccak256(_msg); } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!isPaused, "ERC1155Pausable: token transfer while paused"); } }
// @author: Array // dsc: Array#0007 // tw: @arraythedev // Contact me on twitter
LineComment
maxSupplyOf
function maxSupplyOf(uint256 _tokenId) public pure returns (uint256) { if (_tokenId == 0) return 333; else if (_tokenId == 1) return 3333; else return 0; }
// PUBLIC
LineComment
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 4919, 5106 ] }
57,975
HumansFactoryPass
/contracts/HumansFactoryPass.sol
0x5f6809f90b6ca15663b1fd791d548631df3664a8
Solidity
HumansFactoryPass
contract HumansFactoryPass is ERC1155Supply, Ownable, PaymentSplitter, ReentrancyGuard { using ECDSA for bytes32; using Strings for uint256; using Address for address payable; struct saleParams { string name; bool requireSignature; uint256 startTime; uint256 endTime; uint256 price; uint256 claimable; uint256 supply; uint256 tokenId; } address private signerAddress = 0xDC90586e77086E3A236ad5145df7B4bd7F628067; address[] private _team = [ 0xe2fe6d312138417Cdab7184D70D03B74f2Ce698C, 0xBf4fA1d9b2bAdBeA3373c637168191F07b317c17, 0x0b742B76A4C702262EcDd7DB75965c1754e8623a, 0x3433699934cd2485fa4fd78B04767F7e0075cb82, 0x99f794629E347ac97cb78457e1096dCfBB3b6498, 0xBAd8a212Ea950481871393147eA54c85be325e59, 0x002403988080d56798d2D30C4Ab498Da16bB38e2, 0xC89E9ecF1B2900656ECba77E1Da89600f187A50D, 0xa5bbE2Cd62e275d4Ecaa9a752783823308ACc4d0, 0x23C625789c391463997267BDD8b21e5E266014F6, 0x860Fd5caEb3306A1bcC2bca7d05F97439Df28574 ]; uint256[] private _teamShares = [2, 10, 10, 10, 10, 10, 2, 2, 2, 2, 40]; mapping(uint256 => saleParams) public sales; mapping(string => mapping(address => uint256)) public mintsPerWallet; mapping(string => uint256) public mintsPerSale; string public baseURI; bool public isPaused; string private name_; string private symbol_; event TokensMinted(address mintedBy, uint256 _nb, uint256 tokenId, string saleName); constructor(string memory _name, string memory _symbol) ERC1155("") PaymentSplitter(_team, _teamShares) { name_ = _name; symbol_ = _symbol; } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } // ADMIN function _setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setSignerAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "HF: You look into the deep space only to find nothing but emptiness."); signerAddress = _newAddress; } function withdrawAll() external onlyOwner { for (uint256 i = 0; i < _team.length; i++) { address payable wallet = payable(_team[i]); release(wallet); } } function pause(bool _isPaused) external onlyOwner { isPaused = _isPaused; } function configureSale( string memory _name, bool _requireSignature, uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _claimable, uint256 _supply, uint256 _tokenId, uint256 _id ) external onlyOwner { require(_startTime > 0 && _endTime > 0 && _endTime > _startTime, "HF: Time range is invalid."); sales[_id] = saleParams(_name, _requireSignature, _startTime, _endTime, _price, _claimable, _supply, _tokenId); } // MINT function airdrop( address _to, uint256 _nb, uint256 _tokenId ) external onlyOwner { require(totalSupply(_tokenId) + _nb <= maxSupplyOf(_tokenId), "HF: Not enough tokens left."); _mint(_to, _tokenId, _nb, ""); } function saleMint( uint256 _nb, uint256 _alloc, bytes calldata _signature, uint256 _saleId ) external payable nonReentrant { saleParams memory _sale = sales[_saleId]; require(_sale.startTime > 0 && _sale.endTime > 0, "HF: Sale doesn't exists"); // If a signature is required, the allocation is fetched from it // This allows a dynamic allocation per wallet uint256 alloc = _sale.requireSignature ? _alloc : _sale.claimable; if (_sale.requireSignature) { bytes32 _messageHash = hashMessage(abi.encode(_sale.name, address(this), _msgSender(), _alloc)); require(verifyAddressSigner(_messageHash, _signature), "HF: Invalid signature."); } require(_nb > 0, "HF: Wrong amount requested"); require(block.timestamp > _sale.startTime && block.timestamp < _sale.endTime, "HF: Sale is not active."); require(totalSupply(_sale.tokenId) + _nb <= maxSupplyOf(_sale.tokenId), "HF: Not enough tokens left."); require(mintsPerSale[_sale.name] + _nb <= _sale.supply, "HF: Not enough supply."); require(msg.value >= _nb * _sale.price, "HF: Insufficient amount."); require(mintsPerWallet[_sale.name][_msgSender()] + _nb <= alloc, "HF: Allocation exceeded."); mintsPerWallet[_sale.name][_msgSender()] += _nb; mintsPerSale[_sale.name] += _nb; _mint(_msgSender(), _sale.tokenId, _nb, ""); emit TokensMinted(_msgSender(), _nb, _sale.tokenId, _sale.name); } // PUBLIC function maxSupplyOf(uint256 _tokenId) public pure returns (uint256) { if (_tokenId == 0) return 333; else if (_tokenId == 1) return 3333; else return 0; } function uri(uint256 typeId) public view override returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, typeId.toString())) : baseURI; } // PRIVATE function verifyAddressSigner(bytes32 _messageHash, bytes memory _signature) private view returns (bool) { return signerAddress == _messageHash.toEthSignedMessageHash().recover(_signature); } function hashMessage(bytes memory _msg) private pure returns (bytes32) { return keccak256(_msg); } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!isPaused, "ERC1155Pausable: token transfer while paused"); } }
// @author: Array // dsc: Array#0007 // tw: @arraythedev // Contact me on twitter
LineComment
verifyAddressSigner
function verifyAddressSigner(bytes32 _messageHash, bytes memory _signature) private view returns (bool) { return signerAddress == _messageHash.toEthSignedMessageHash().recover(_signature); }
// PRIVATE
LineComment
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 5317, 5523 ] }
57,976
HumansFactoryPass
/contracts/HumansFactoryPass.sol
0x5f6809f90b6ca15663b1fd791d548631df3664a8
Solidity
HumansFactoryPass
contract HumansFactoryPass is ERC1155Supply, Ownable, PaymentSplitter, ReentrancyGuard { using ECDSA for bytes32; using Strings for uint256; using Address for address payable; struct saleParams { string name; bool requireSignature; uint256 startTime; uint256 endTime; uint256 price; uint256 claimable; uint256 supply; uint256 tokenId; } address private signerAddress = 0xDC90586e77086E3A236ad5145df7B4bd7F628067; address[] private _team = [ 0xe2fe6d312138417Cdab7184D70D03B74f2Ce698C, 0xBf4fA1d9b2bAdBeA3373c637168191F07b317c17, 0x0b742B76A4C702262EcDd7DB75965c1754e8623a, 0x3433699934cd2485fa4fd78B04767F7e0075cb82, 0x99f794629E347ac97cb78457e1096dCfBB3b6498, 0xBAd8a212Ea950481871393147eA54c85be325e59, 0x002403988080d56798d2D30C4Ab498Da16bB38e2, 0xC89E9ecF1B2900656ECba77E1Da89600f187A50D, 0xa5bbE2Cd62e275d4Ecaa9a752783823308ACc4d0, 0x23C625789c391463997267BDD8b21e5E266014F6, 0x860Fd5caEb3306A1bcC2bca7d05F97439Df28574 ]; uint256[] private _teamShares = [2, 10, 10, 10, 10, 10, 2, 2, 2, 2, 40]; mapping(uint256 => saleParams) public sales; mapping(string => mapping(address => uint256)) public mintsPerWallet; mapping(string => uint256) public mintsPerSale; string public baseURI; bool public isPaused; string private name_; string private symbol_; event TokensMinted(address mintedBy, uint256 _nb, uint256 tokenId, string saleName); constructor(string memory _name, string memory _symbol) ERC1155("") PaymentSplitter(_team, _teamShares) { name_ = _name; symbol_ = _symbol; } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } // ADMIN function _setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setSignerAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "HF: You look into the deep space only to find nothing but emptiness."); signerAddress = _newAddress; } function withdrawAll() external onlyOwner { for (uint256 i = 0; i < _team.length; i++) { address payable wallet = payable(_team[i]); release(wallet); } } function pause(bool _isPaused) external onlyOwner { isPaused = _isPaused; } function configureSale( string memory _name, bool _requireSignature, uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _claimable, uint256 _supply, uint256 _tokenId, uint256 _id ) external onlyOwner { require(_startTime > 0 && _endTime > 0 && _endTime > _startTime, "HF: Time range is invalid."); sales[_id] = saleParams(_name, _requireSignature, _startTime, _endTime, _price, _claimable, _supply, _tokenId); } // MINT function airdrop( address _to, uint256 _nb, uint256 _tokenId ) external onlyOwner { require(totalSupply(_tokenId) + _nb <= maxSupplyOf(_tokenId), "HF: Not enough tokens left."); _mint(_to, _tokenId, _nb, ""); } function saleMint( uint256 _nb, uint256 _alloc, bytes calldata _signature, uint256 _saleId ) external payable nonReentrant { saleParams memory _sale = sales[_saleId]; require(_sale.startTime > 0 && _sale.endTime > 0, "HF: Sale doesn't exists"); // If a signature is required, the allocation is fetched from it // This allows a dynamic allocation per wallet uint256 alloc = _sale.requireSignature ? _alloc : _sale.claimable; if (_sale.requireSignature) { bytes32 _messageHash = hashMessage(abi.encode(_sale.name, address(this), _msgSender(), _alloc)); require(verifyAddressSigner(_messageHash, _signature), "HF: Invalid signature."); } require(_nb > 0, "HF: Wrong amount requested"); require(block.timestamp > _sale.startTime && block.timestamp < _sale.endTime, "HF: Sale is not active."); require(totalSupply(_sale.tokenId) + _nb <= maxSupplyOf(_sale.tokenId), "HF: Not enough tokens left."); require(mintsPerSale[_sale.name] + _nb <= _sale.supply, "HF: Not enough supply."); require(msg.value >= _nb * _sale.price, "HF: Insufficient amount."); require(mintsPerWallet[_sale.name][_msgSender()] + _nb <= alloc, "HF: Allocation exceeded."); mintsPerWallet[_sale.name][_msgSender()] += _nb; mintsPerSale[_sale.name] += _nb; _mint(_msgSender(), _sale.tokenId, _nb, ""); emit TokensMinted(_msgSender(), _nb, _sale.tokenId, _sale.name); } // PUBLIC function maxSupplyOf(uint256 _tokenId) public pure returns (uint256) { if (_tokenId == 0) return 333; else if (_tokenId == 1) return 3333; else return 0; } function uri(uint256 typeId) public view override returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, typeId.toString())) : baseURI; } // PRIVATE function verifyAddressSigner(bytes32 _messageHash, bytes memory _signature) private view returns (bool) { return signerAddress == _messageHash.toEthSignedMessageHash().recover(_signature); } function hashMessage(bytes memory _msg) private pure returns (bytes32) { return keccak256(_msg); } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!isPaused, "ERC1155Pausable: token transfer while paused"); } }
// @author: Array // dsc: Array#0007 // tw: @arraythedev // Contact me on twitter
LineComment
_beforeTokenTransfer
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!isPaused, "ERC1155Pausable: token transfer while paused"); }
/** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 5782, 6167 ] }
57,977
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
toRlpItem
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); }
/* * @param item RLP encoded bytes */
Comment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 359, 681 ] }
57,978
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
toList
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; }
/* * @param item RLP encoded list in bytes */
Comment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 743, 1461 ] }
57,979
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
isList
function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; }
// @return indicator whether encoded payload is a list. negate this function call for isData.
LineComment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 1561, 1844 ] }
57,980
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
toRlpBytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; }
// @returns raw rlp encoding in bytes
LineComment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 1937, 2259 ] }
57,981
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
toUintStrict
function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; }
// enforces 32 byte length
LineComment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 3374, 3863 ] }
57,982
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
numItems
function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; }
// @return number of payload items inside an encoded list.
LineComment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 4522, 5172 ] }
57,983
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
_itemLength
function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; }
// @return entire rlp item byte length
LineComment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 5217, 6464 ] }
57,984
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
_payloadOffset
function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; }
// @return number of bytes until the data
LineComment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 6512, 7071 ] }
57,985
PoolTogetherEVMBridgeRoot
contracts/libraries/RLPReader.sol
0xfe6c5ae087366a7119f12946d07e04c94bb7a048
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
copy
function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } }
/* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */
Comment
v0.7.3+commit.9bfce1f6
MIT
{ "func_code_index": [ 7225, 7966 ] }
57,986
CompoundProtocolAdapter
contracts/interfaces/CompoundInterfaces.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
ICToken
interface ICToken { function comptroller() external view returns (address); function underlying() external view returns (address); function name() external view returns (string memory); function totalSupply() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); function totalBorrows() external view returns (uint256); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function accrualBlockNumber() external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint); function interestRateModel() external view returns (IInterestRateModel); function balanceOf(address account) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint); function mint(uint256 mintAmount) external returns (uint256); function mint() external payable; function redeem(uint256 tokenAmount) external returns (uint256); function redeemUnderlying(uint256 underlyingAmount) external returns (uint256); function borrow(uint borrowAmount) external returns (uint); // Used to check if a cream market is for an SLP token function sushi() external view returns (address); }
sushi
function sushi() external view returns (address);
// Used to check if a cream market is for an SLP token
LineComment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1480, 1531 ] }
57,987
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
addToken
function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; }
/** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 5165, 5601 ] }
57,988
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
placeOrder
function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); }
/** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 6174, 6461 ] }
57,989
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
placeValidFromOrders
function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } }
/** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 7250, 7945 ] }
57,990
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
cancelOrders
function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } }
/** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 8447, 8955 ] }
57,991
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
replaceOrders
function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); }
/** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 9837, 10338 ] }
57,992
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
submitSolution
function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); }
/** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 11939, 16091 ] }
57,993
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
tokenAddressToIdMap
function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); }
/** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 16301, 16450 ] }
57,994
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
tokenIdToAddressMap
function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); }
/** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 16635, 16787 ] }
57,995
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
hasToken
function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); }
/** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 16998, 17139 ] }
57,996
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
getEncodedUserOrders
function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; }
/** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 17352, 17735 ] }
57,997
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
getEncodedOrders
function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; }
/** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 17886, 18413 ] }
57,998
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
getCurrentObjectiveValue
function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } }
/** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 18801, 19049 ] }
57,999
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
placeOrderInternal
function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; }
/** * Private Functions */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 19096, 20107 ] }
58,000
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
grantRewardToSolutionSubmitter
function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); }
/** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 20270, 20493 ] }
58,001
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
burnPreviousAuctionFees
function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } }
/** @dev called during solution submission to burn fees from previous auction */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 20589, 20771 ] }
58,002
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
updateCurrentPrices
function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } }
/** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 21063, 21468 ] }
58,003
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
updateRemainingOrder
function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); }
/** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 21802, 22021 ] }
58,004
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
revertRemainingOrder
function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); }
/** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 22358, 22577 ] }
58,005
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
documentTrades
function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; }
/** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 23102, 23672 ] }
58,006
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
undoCurrentSolution
function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } }
/** @dev reverts all relevant contract storage relating to an overwritten auction solution. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 23782, 25146 ] }
58,007
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
checkAndOverrideObjectiveValue
function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; }
/** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 25364, 25687 ] }
58,008
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
evaluateUtility
function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); }
/** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 26044, 26787 ] }
58,009
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
evaluateDisregardedUtility
function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); }
/** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 27582, 28320 ] }
58,010
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
getExecutedSellAmount
function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); }
/** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 29461, 29884 ] }
58,011
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
currentBatchHasSolution
function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; }
/** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 30070, 30213 ] }
58,012
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
getTradedAmounts
function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); }
/** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 30516, 30892 ] }
58,013
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
isObjectiveValueSufficientlyImproved
function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); }
/** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 31180, 31416 ] }
58,014
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
checkOrderValidity
function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; }
/** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 31715, 31905 ] }
58,015
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
getRemainingAmount
function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; }
/** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 32108, 32259 ] }
58,016
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
encodeAuctionElement
function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; }
/** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 32585, 33415 ] }
58,017
BatchExchange
contracts/BatchExchange.sol
0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5
Solidity
BatchExchange
contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */
NatSpecMultiLine
verifyAmountThreshold
function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; }
/** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */
NatSpecMultiLine
v0.5.6+commit.b259423e
GNU GPLv3
bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb
{ "func_code_index": [ 33584, 33865 ] }
58,018
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 89, 476 ] }
58,019
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 560, 840 ] }
58,020
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 954, 1070 ] }
58,021
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 1134, 1264 ] }
58,022
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); }
/** * @dev Allows the current owner to relinquish control of the contract. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 638, 755 ] }
58,023
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 920, 1028 ] }
58,024
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
/** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 1166, 1344 ] }
58,025
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev total number of tokens in existence */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 199, 287 ] }
58,026
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 445, 777 ] }
58,027
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 983, 1087 ] }
58,028
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
BurnableToken
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } }
/** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */
NatSpecMultiLine
burn
function burn(uint256 _value) public { _burn(msg.sender, _value); }
/** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 212, 290 ] }
58,029
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 401, 891 ] }
58,030
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 1523, 1718 ] }
58,031
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 2042, 2207 ] }
58,032
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 2673, 2980 ] }
58,033
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
decreaseApproval
function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 3451, 3894 ] }
58,034
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
StandardBurnableToken
contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } }
/** * @title Standard Burnable Token * @dev Adds burnFrom method to ERC20 implementations */
NatSpecMultiLine
burnFrom
function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); }
/** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 311, 690 ] }
58,035
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
pause
function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); }
/** * @dev called by the owner to pause, triggers stopped state */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 513, 609 ] }
58,036
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
unpause
function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); }
/** * @dev called by the owner to unpause, returns to normal state */
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 693, 791 ] }
58,037
BoyCoin
BoyCoin.sol
0x368e178bf686a2637a58d0f2ed319ccd24cf4484
Solidity
BaseERC20Token
contract BaseERC20Token is StandardBurnableToken, PausableToken, DetailedERC20 { constructor( uint256 _initialAmount, uint8 _decimalUnits, string _tokenName, string _tokenSymbol ) DetailedERC20(_tokenName, _tokenSymbol, _decimalUnits) public { totalSupply_ = _initialAmount; balances[msg.sender] = totalSupply_; } // override the burnable token's "Burn" function: don't allow tokens to // be burned when paused function _burn(address _from, uint256 _value) internal whenNotPaused { super._burn(_from, _value); } }
/** * A base token for the BoyCoin (or any other coin with similar behavior). * Compatible with contracts and UIs expecting a ERC20 token. * Provides also a convenience method to burn tokens, permanently removing them from the pool; * the intent of this convenience method is for users who wish to burn tokens * (as they always can via a transfer to an unowned address or self-destructing * contract) to do so in a way that is then reflected in the token's total supply. */
NatSpecMultiLine
_burn
function _burn(address _from, uint256 _value) internal whenNotPaused { super._burn(_from, _value); }
// override the burnable token's "Burn" function: don't allow tokens to // be burned when paused
LineComment
v0.4.23+commit.124ca40d
MIT
bzzr://1f6cbe41190aeb9442b4505fdebc619da85d57064e36d1b98a50d4cf00bd0c4b
{ "func_code_index": [ 461, 572 ] }
58,038
CompoundProtocolAdapter
contracts/adapters/compound/CErc20Adapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CErc20Adapter
contract CErc20Adapter is AbstractErc20Adapter() { using MinimalSignedMath for uint256; using LowGasSafeMath for uint256; using TransferHelper for address; /* ========== Constants ========== */ IComptroller internal constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address internal constant cComp = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /* ========== Internal Queries ========== */ function _protocolName() internal view virtual override returns (string memory) { return "Compound"; } /* ========== Metadata ========== */ function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); } /* ========== Conversion Queries ========== */ function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); } function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) { return underlyingAmount .mul(1e18) / CTokenParams.currentExchangeRate(token); } /* ========== Performance Queries ========== */ function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); } function getRewardsAPR() public view returns (uint256) { ICToken cToken = ICToken(token); ( ,uint256 cash, uint256 borrows, uint256 reserves, ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 totalLiquidity = cash.add(borrows).sub(reserves); cToken.getCash().add(cToken.totalBorrows()).sub(cToken.totalReserves()); return getRewardsAPR(ICToken(token), totalLiquidity); } function getAPR() public view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(liquidityDelta).add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior.add(liquidityDelta), borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getRevenueBreakdown() external view override returns ( address[] memory assets, uint256[] memory aprs ) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); uint256 baseAPR = IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400); uint256 rewardsAPR = getRewardsAPR(cToken, liquidityTotal); uint256 size = rewardsAPR > 0 ? 2 : 1; assets = new address[](size); aprs = new uint256[](size); assets[0] = underlying; aprs[0] = baseAPR; if (rewardsAPR > 0) { assets[1] = comp; aprs[1] = rewardsAPR; } } /* ========== Caller Balance Queries ========== */ function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); } /* ========== Internal Actions ========== */ function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); } function _approve() internal virtual override { underlying.safeApproveMax(token); } function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) { address _token = token; require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed"); amountMinted = IERC20(_token).balanceOf(address(this)); } function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) { require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed"); amountReceived = IERC20(underlying).balanceOf(address(this)); _claimRewardsIfAny(msg.sender); } function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) { amountBurned = toWrappedAmount(amountUnderlying); token.safeTransferFrom(msg.sender, address(this), amountBurned); require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CErc20: Burn failed"); _claimRewardsIfAny(msg.sender); } }
_protocolName
function _protocolName() internal view virtual override returns (string memory) { return "Compound"; }
/* ========== Internal Queries ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 513, 623 ] }
58,039
CompoundProtocolAdapter
contracts/adapters/compound/CErc20Adapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CErc20Adapter
contract CErc20Adapter is AbstractErc20Adapter() { using MinimalSignedMath for uint256; using LowGasSafeMath for uint256; using TransferHelper for address; /* ========== Constants ========== */ IComptroller internal constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address internal constant cComp = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /* ========== Internal Queries ========== */ function _protocolName() internal view virtual override returns (string memory) { return "Compound"; } /* ========== Metadata ========== */ function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); } /* ========== Conversion Queries ========== */ function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); } function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) { return underlyingAmount .mul(1e18) / CTokenParams.currentExchangeRate(token); } /* ========== Performance Queries ========== */ function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); } function getRewardsAPR() public view returns (uint256) { ICToken cToken = ICToken(token); ( ,uint256 cash, uint256 borrows, uint256 reserves, ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 totalLiquidity = cash.add(borrows).sub(reserves); cToken.getCash().add(cToken.totalBorrows()).sub(cToken.totalReserves()); return getRewardsAPR(ICToken(token), totalLiquidity); } function getAPR() public view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(liquidityDelta).add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior.add(liquidityDelta), borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getRevenueBreakdown() external view override returns ( address[] memory assets, uint256[] memory aprs ) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); uint256 baseAPR = IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400); uint256 rewardsAPR = getRewardsAPR(cToken, liquidityTotal); uint256 size = rewardsAPR > 0 ? 2 : 1; assets = new address[](size); aprs = new uint256[](size); assets[0] = underlying; aprs[0] = baseAPR; if (rewardsAPR > 0) { assets[1] = comp; aprs[1] = rewardsAPR; } } /* ========== Caller Balance Queries ========== */ function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); } /* ========== Internal Actions ========== */ function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); } function _approve() internal virtual override { underlying.safeApproveMax(token); } function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) { address _token = token; require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed"); amountMinted = IERC20(_token).balanceOf(address(this)); } function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) { require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed"); amountReceived = IERC20(underlying).balanceOf(address(this)); _claimRewardsIfAny(msg.sender); } function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) { amountBurned = toWrappedAmount(amountUnderlying); token.safeTransferFrom(msg.sender, address(this), amountBurned); require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CErc20: Burn failed"); _claimRewardsIfAny(msg.sender); } }
availableLiquidity
function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); }
/* ========== Metadata ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 663, 787 ] }
58,040
CompoundProtocolAdapter
contracts/adapters/compound/CErc20Adapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CErc20Adapter
contract CErc20Adapter is AbstractErc20Adapter() { using MinimalSignedMath for uint256; using LowGasSafeMath for uint256; using TransferHelper for address; /* ========== Constants ========== */ IComptroller internal constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address internal constant cComp = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /* ========== Internal Queries ========== */ function _protocolName() internal view virtual override returns (string memory) { return "Compound"; } /* ========== Metadata ========== */ function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); } /* ========== Conversion Queries ========== */ function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); } function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) { return underlyingAmount .mul(1e18) / CTokenParams.currentExchangeRate(token); } /* ========== Performance Queries ========== */ function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); } function getRewardsAPR() public view returns (uint256) { ICToken cToken = ICToken(token); ( ,uint256 cash, uint256 borrows, uint256 reserves, ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 totalLiquidity = cash.add(borrows).sub(reserves); cToken.getCash().add(cToken.totalBorrows()).sub(cToken.totalReserves()); return getRewardsAPR(ICToken(token), totalLiquidity); } function getAPR() public view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(liquidityDelta).add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior.add(liquidityDelta), borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getRevenueBreakdown() external view override returns ( address[] memory assets, uint256[] memory aprs ) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); uint256 baseAPR = IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400); uint256 rewardsAPR = getRewardsAPR(cToken, liquidityTotal); uint256 size = rewardsAPR > 0 ? 2 : 1; assets = new address[](size); aprs = new uint256[](size); assets[0] = underlying; aprs[0] = baseAPR; if (rewardsAPR > 0) { assets[1] = comp; aprs[1] = rewardsAPR; } } /* ========== Caller Balance Queries ========== */ function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); } /* ========== Internal Actions ========== */ function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); } function _approve() internal virtual override { underlying.safeApproveMax(token); } function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) { address _token = token; require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed"); amountMinted = IERC20(_token).balanceOf(address(this)); } function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) { require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed"); amountReceived = IERC20(underlying).balanceOf(address(this)); _claimRewardsIfAny(msg.sender); } function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) { amountBurned = toWrappedAmount(amountUnderlying); token.safeTransferFrom(msg.sender, address(this), amountBurned); require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CErc20: Burn failed"); _claimRewardsIfAny(msg.sender); } }
toUnderlyingAmount
function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); }
/* ========== Conversion Queries ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 837, 1044 ] }
58,041
CompoundProtocolAdapter
contracts/adapters/compound/CErc20Adapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CErc20Adapter
contract CErc20Adapter is AbstractErc20Adapter() { using MinimalSignedMath for uint256; using LowGasSafeMath for uint256; using TransferHelper for address; /* ========== Constants ========== */ IComptroller internal constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address internal constant cComp = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /* ========== Internal Queries ========== */ function _protocolName() internal view virtual override returns (string memory) { return "Compound"; } /* ========== Metadata ========== */ function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); } /* ========== Conversion Queries ========== */ function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); } function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) { return underlyingAmount .mul(1e18) / CTokenParams.currentExchangeRate(token); } /* ========== Performance Queries ========== */ function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); } function getRewardsAPR() public view returns (uint256) { ICToken cToken = ICToken(token); ( ,uint256 cash, uint256 borrows, uint256 reserves, ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 totalLiquidity = cash.add(borrows).sub(reserves); cToken.getCash().add(cToken.totalBorrows()).sub(cToken.totalReserves()); return getRewardsAPR(ICToken(token), totalLiquidity); } function getAPR() public view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(liquidityDelta).add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior.add(liquidityDelta), borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getRevenueBreakdown() external view override returns ( address[] memory assets, uint256[] memory aprs ) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); uint256 baseAPR = IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400); uint256 rewardsAPR = getRewardsAPR(cToken, liquidityTotal); uint256 size = rewardsAPR > 0 ? 2 : 1; assets = new address[](size); aprs = new uint256[](size); assets[0] = underlying; aprs[0] = baseAPR; if (rewardsAPR > 0) { assets[1] = comp; aprs[1] = rewardsAPR; } } /* ========== Caller Balance Queries ========== */ function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); } /* ========== Internal Actions ========== */ function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); } function _approve() internal virtual override { underlying.safeApproveMax(token); } function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) { address _token = token; require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed"); amountMinted = IERC20(_token).balanceOf(address(this)); } function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) { require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed"); amountReceived = IERC20(underlying).balanceOf(address(this)); _claimRewardsIfAny(msg.sender); } function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) { amountBurned = toWrappedAmount(amountUnderlying); token.safeTransferFrom(msg.sender, address(this), amountBurned); require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CErc20: Burn failed"); _claimRewardsIfAny(msg.sender); } }
getRewardsAPR
function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); }
/* ========== Performance Queries ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1288, 1798 ] }
58,042
CompoundProtocolAdapter
contracts/adapters/compound/CErc20Adapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CErc20Adapter
contract CErc20Adapter is AbstractErc20Adapter() { using MinimalSignedMath for uint256; using LowGasSafeMath for uint256; using TransferHelper for address; /* ========== Constants ========== */ IComptroller internal constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address internal constant cComp = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /* ========== Internal Queries ========== */ function _protocolName() internal view virtual override returns (string memory) { return "Compound"; } /* ========== Metadata ========== */ function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); } /* ========== Conversion Queries ========== */ function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); } function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) { return underlyingAmount .mul(1e18) / CTokenParams.currentExchangeRate(token); } /* ========== Performance Queries ========== */ function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); } function getRewardsAPR() public view returns (uint256) { ICToken cToken = ICToken(token); ( ,uint256 cash, uint256 borrows, uint256 reserves, ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 totalLiquidity = cash.add(borrows).sub(reserves); cToken.getCash().add(cToken.totalBorrows()).sub(cToken.totalReserves()); return getRewardsAPR(ICToken(token), totalLiquidity); } function getAPR() public view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(liquidityDelta).add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior.add(liquidityDelta), borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getRevenueBreakdown() external view override returns ( address[] memory assets, uint256[] memory aprs ) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); uint256 baseAPR = IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400); uint256 rewardsAPR = getRewardsAPR(cToken, liquidityTotal); uint256 size = rewardsAPR > 0 ? 2 : 1; assets = new address[](size); aprs = new uint256[](size); assets[0] = underlying; aprs[0] = baseAPR; if (rewardsAPR > 0) { assets[1] = comp; aprs[1] = rewardsAPR; } } /* ========== Caller Balance Queries ========== */ function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); } /* ========== Internal Actions ========== */ function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); } function _approve() internal virtual override { underlying.safeApproveMax(token); } function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) { address _token = token; require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed"); amountMinted = IERC20(_token).balanceOf(address(this)); } function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) { require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed"); amountReceived = IERC20(underlying).balanceOf(address(this)); _claimRewardsIfAny(msg.sender); } function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) { amountBurned = toWrappedAmount(amountUnderlying); token.safeTransferFrom(msg.sender, address(this), amountBurned); require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CErc20: Burn failed"); _claimRewardsIfAny(msg.sender); } }
balanceUnderlying
function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); }
/* ========== Caller Balance Queries ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 4522, 4676 ] }
58,043
CompoundProtocolAdapter
contracts/adapters/compound/CErc20Adapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CErc20Adapter
contract CErc20Adapter is AbstractErc20Adapter() { using MinimalSignedMath for uint256; using LowGasSafeMath for uint256; using TransferHelper for address; /* ========== Constants ========== */ IComptroller internal constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address internal constant cComp = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /* ========== Internal Queries ========== */ function _protocolName() internal view virtual override returns (string memory) { return "Compound"; } /* ========== Metadata ========== */ function availableLiquidity() public view override returns (uint256) { return IERC20(underlying).balanceOf(token); } /* ========== Conversion Queries ========== */ function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) { return ( tokenAmount .mul(CTokenParams.currentExchangeRate(token)) / uint256(1e18) ); } function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) { return underlyingAmount .mul(1e18) / CTokenParams.currentExchangeRate(token); } /* ========== Performance Queries ========== */ function getRewardsAPR( ICToken cToken, uint256 _totalLiquidity ) internal view returns (uint256) { IPriceOracle oracle = comptroller.oracle(); uint256 compPrice = oracle.getUnderlyingPrice(cComp); uint256 tokenPrice = oracle.getUnderlyingPrice(address(cToken)); if (compPrice == 0 || tokenPrice == 0) return 0; uint256 annualRewards = comptroller.compSpeeds(address(cToken)).mul(2102400).mul(compPrice); return annualRewards.mul(1e18) / _totalLiquidity.mul(tokenPrice); } function getRewardsAPR() public view returns (uint256) { ICToken cToken = ICToken(token); ( ,uint256 cash, uint256 borrows, uint256 reserves, ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 totalLiquidity = cash.add(borrows).sub(reserves); cToken.getCash().add(cToken.totalBorrows()).sub(cToken.totalReserves()); return getRewardsAPR(ICToken(token), totalLiquidity); } function getAPR() public view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(liquidityDelta).add(borrowsPrior).sub(reservesPrior); return IInterestRateModel(model).getSupplyRate( cashPrior.add(liquidityDelta), borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400).add(getRewardsAPR(cToken, liquidityTotal)); } function getRevenueBreakdown() external view override returns ( address[] memory assets, uint256[] memory aprs ) { ICToken cToken = ICToken(token); ( address model, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 reserveFactorMantissa ) = CTokenParams.getInterestRateParameters(address(cToken)); uint256 liquidityTotal = cashPrior.add(borrowsPrior).sub(reservesPrior); uint256 baseAPR = IInterestRateModel(model).getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ).mul(2102400); uint256 rewardsAPR = getRewardsAPR(cToken, liquidityTotal); uint256 size = rewardsAPR > 0 ? 2 : 1; assets = new address[](size); aprs = new uint256[](size); assets[0] = underlying; aprs[0] = baseAPR; if (rewardsAPR > 0) { assets[1] = comp; aprs[1] = rewardsAPR; } } /* ========== Caller Balance Queries ========== */ function balanceUnderlying() external view virtual override returns (uint256) { return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender)); } /* ========== Internal Actions ========== */ function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); } function _approve() internal virtual override { underlying.safeApproveMax(token); } function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) { address _token = token; require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed"); amountMinted = IERC20(_token).balanceOf(address(this)); } function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) { require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed"); amountReceived = IERC20(underlying).balanceOf(address(this)); _claimRewardsIfAny(msg.sender); } function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) { amountBurned = toWrappedAmount(amountUnderlying); token.safeTransferFrom(msg.sender, address(this), amountBurned); require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CErc20: Burn failed"); _claimRewardsIfAny(msg.sender); } }
_claimRewardsIfAny
function _claimRewardsIfAny(address account) internal { address[] memory holders = new address[](1); address[] memory cTokens = new address[](1); holders[0] = account; cTokens[0] = token; comptroller.claimComp(holders, cTokens, false, true); }
/* ========== Internal Actions ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 4724, 4991 ] }
58,044
CompoundProtocolAdapter
contracts/protocols/CompoundProtocolAdapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CompoundProtocolAdapter
contract CompoundProtocolAdapter is AbstractProtocolAdapter { using CloneLibrary for address; /* ========== Constants ========== */ IComptroller public constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant interestRateModelV1 = 0xBAE04CbF96391086dC643e842b517734E214D698; address public immutable erc20AdapterImplementationV1; address public immutable erc20AdapterImplementation; address public immutable etherAdapterImplementation; /* ========== Constructor ========== */ constructor(IAdapterRegistry _registry) AbstractProtocolAdapter(_registry) { erc20AdapterImplementationV1 = address(new C1Erc20Adapter()); erc20AdapterImplementation = address(new CErc20Adapter()); etherAdapterImplementation = address(new CEtherAdapter()); } /* ========== Internal Actions ========== */ function deployAdapter(address cToken) internal virtual override returns (address adapter) { address underlying; // The call to underlying() will use all the gas sent if it fails, // so we specify a maximum of 25k gas. The contract will only use ~2k // but this protects against all likely changes to the gas schedule. try ICToken(cToken).underlying{gas: 25000}() returns (address _underlying) { underlying = _underlying; if (underlying == address(0)) { underlying = weth; } } catch { underlying = weth; } if (underlying == weth) { adapter = etherAdapterImplementation.createClone(); } else if (address(ICToken(cToken).interestRateModel()) == interestRateModelV1) { adapter = erc20AdapterImplementationV1.createClone(); } else { adapter = erc20AdapterImplementation.createClone(); } CErc20Adapter(adapter).initialize(underlying, cToken); } /* ========== Public Queries ========== */ function protocol() external pure virtual override returns (string memory) { return "Compound"; } function getUnmapped() public view virtual override returns (address[] memory cTokens) { cTokens = toAddressArray(comptroller.getAllMarkets()); uint256 len = cTokens.length; uint256 prevLen = totalMapped; if (len == prevLen) { assembly { mstore(cTokens, 0) } } else { assembly { cTokens := add(cTokens, mul(prevLen, 32)) mstore(cTokens, sub(len, prevLen)) } } } function toAddressArray(ICToken[] memory cTokens) internal pure returns (address[] memory arr) { assembly { arr := cTokens } } /* ========== Internal Queries ========== */ function isAdapterMarketFrozen(address adapter) internal view virtual override returns (bool) { return isTokenMarketFrozen(IErc20Adapter(adapter).token()); } function isTokenMarketFrozen(address cToken) internal view virtual override returns (bool) { if (comptroller.mintGuardianPaused(cToken)) { return true; } return IERC20(cToken).totalSupply() == 0; } }
deployAdapter
function deployAdapter(address cToken) internal virtual override returns (address adapter) { address underlying; // The call to underlying() will use all the gas sent if it fails, // so we specify a maximum of 25k gas. The contract will only use ~2k // but this protects against all likely changes to the gas schedule. try ICToken(cToken).underlying{gas: 25000}() returns (address _underlying) { underlying = _underlying; if (underlying == address(0)) { underlying = weth; } } catch { underlying = weth; } if (underlying == weth) { adapter = etherAdapterImplementation.createClone(); } else if (address(ICToken(cToken).interestRateModel()) == interestRateModelV1) { adapter = erc20AdapterImplementationV1.createClone(); } else { adapter = erc20AdapterImplementation.createClone(); } CErc20Adapter(adapter).initialize(underlying, cToken); }
/* ========== Internal Actions ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 862, 1803 ] }
58,045
CompoundProtocolAdapter
contracts/protocols/CompoundProtocolAdapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CompoundProtocolAdapter
contract CompoundProtocolAdapter is AbstractProtocolAdapter { using CloneLibrary for address; /* ========== Constants ========== */ IComptroller public constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant interestRateModelV1 = 0xBAE04CbF96391086dC643e842b517734E214D698; address public immutable erc20AdapterImplementationV1; address public immutable erc20AdapterImplementation; address public immutable etherAdapterImplementation; /* ========== Constructor ========== */ constructor(IAdapterRegistry _registry) AbstractProtocolAdapter(_registry) { erc20AdapterImplementationV1 = address(new C1Erc20Adapter()); erc20AdapterImplementation = address(new CErc20Adapter()); etherAdapterImplementation = address(new CEtherAdapter()); } /* ========== Internal Actions ========== */ function deployAdapter(address cToken) internal virtual override returns (address adapter) { address underlying; // The call to underlying() will use all the gas sent if it fails, // so we specify a maximum of 25k gas. The contract will only use ~2k // but this protects against all likely changes to the gas schedule. try ICToken(cToken).underlying{gas: 25000}() returns (address _underlying) { underlying = _underlying; if (underlying == address(0)) { underlying = weth; } } catch { underlying = weth; } if (underlying == weth) { adapter = etherAdapterImplementation.createClone(); } else if (address(ICToken(cToken).interestRateModel()) == interestRateModelV1) { adapter = erc20AdapterImplementationV1.createClone(); } else { adapter = erc20AdapterImplementation.createClone(); } CErc20Adapter(adapter).initialize(underlying, cToken); } /* ========== Public Queries ========== */ function protocol() external pure virtual override returns (string memory) { return "Compound"; } function getUnmapped() public view virtual override returns (address[] memory cTokens) { cTokens = toAddressArray(comptroller.getAllMarkets()); uint256 len = cTokens.length; uint256 prevLen = totalMapped; if (len == prevLen) { assembly { mstore(cTokens, 0) } } else { assembly { cTokens := add(cTokens, mul(prevLen, 32)) mstore(cTokens, sub(len, prevLen)) } } } function toAddressArray(ICToken[] memory cTokens) internal pure returns (address[] memory arr) { assembly { arr := cTokens } } /* ========== Internal Queries ========== */ function isAdapterMarketFrozen(address adapter) internal view virtual override returns (bool) { return isTokenMarketFrozen(IErc20Adapter(adapter).token()); } function isTokenMarketFrozen(address cToken) internal view virtual override returns (bool) { if (comptroller.mintGuardianPaused(cToken)) { return true; } return IERC20(cToken).totalSupply() == 0; } }
protocol
function protocol() external pure virtual override returns (string memory) { return "Compound"; }
/* ========== Public Queries ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1849, 1954 ] }
58,046
CompoundProtocolAdapter
contracts/protocols/CompoundProtocolAdapter.sol
0x7f77389b868718b5351433d8031d49921cd72ace
Solidity
CompoundProtocolAdapter
contract CompoundProtocolAdapter is AbstractProtocolAdapter { using CloneLibrary for address; /* ========== Constants ========== */ IComptroller public constant comptroller = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant interestRateModelV1 = 0xBAE04CbF96391086dC643e842b517734E214D698; address public immutable erc20AdapterImplementationV1; address public immutable erc20AdapterImplementation; address public immutable etherAdapterImplementation; /* ========== Constructor ========== */ constructor(IAdapterRegistry _registry) AbstractProtocolAdapter(_registry) { erc20AdapterImplementationV1 = address(new C1Erc20Adapter()); erc20AdapterImplementation = address(new CErc20Adapter()); etherAdapterImplementation = address(new CEtherAdapter()); } /* ========== Internal Actions ========== */ function deployAdapter(address cToken) internal virtual override returns (address adapter) { address underlying; // The call to underlying() will use all the gas sent if it fails, // so we specify a maximum of 25k gas. The contract will only use ~2k // but this protects against all likely changes to the gas schedule. try ICToken(cToken).underlying{gas: 25000}() returns (address _underlying) { underlying = _underlying; if (underlying == address(0)) { underlying = weth; } } catch { underlying = weth; } if (underlying == weth) { adapter = etherAdapterImplementation.createClone(); } else if (address(ICToken(cToken).interestRateModel()) == interestRateModelV1) { adapter = erc20AdapterImplementationV1.createClone(); } else { adapter = erc20AdapterImplementation.createClone(); } CErc20Adapter(adapter).initialize(underlying, cToken); } /* ========== Public Queries ========== */ function protocol() external pure virtual override returns (string memory) { return "Compound"; } function getUnmapped() public view virtual override returns (address[] memory cTokens) { cTokens = toAddressArray(comptroller.getAllMarkets()); uint256 len = cTokens.length; uint256 prevLen = totalMapped; if (len == prevLen) { assembly { mstore(cTokens, 0) } } else { assembly { cTokens := add(cTokens, mul(prevLen, 32)) mstore(cTokens, sub(len, prevLen)) } } } function toAddressArray(ICToken[] memory cTokens) internal pure returns (address[] memory arr) { assembly { arr := cTokens } } /* ========== Internal Queries ========== */ function isAdapterMarketFrozen(address adapter) internal view virtual override returns (bool) { return isTokenMarketFrozen(IErc20Adapter(adapter).token()); } function isTokenMarketFrozen(address cToken) internal view virtual override returns (bool) { if (comptroller.mintGuardianPaused(cToken)) { return true; } return IERC20(cToken).totalSupply() == 0; } }
isAdapterMarketFrozen
function isAdapterMarketFrozen(address adapter) internal view virtual override returns (bool) { return isTokenMarketFrozen(IErc20Adapter(adapter).token()); }
/* ========== Internal Queries ========== */
Comment
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 2563, 2728 ] }
58,047
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 987, 1103 ] }
58,048
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 1323, 1448 ] }
58,049
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 1792, 2074 ] }
58,050
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 2582, 2795 ] }
58,051
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 3326, 3689 ] }
58,052
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 3972, 4124 ] }
58,053
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 4479, 4817 ] }
58,054
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
function () external payable { revert(); }
// ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 5009, 5070 ] }
58,055
locashToken
locashToken.sol
0x248a0316d862f6c7945067f8bd12c035bb4a12d5
Solidity
locashToken
contract locashToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "LOCA"; name = "locashToken"; decimals = 18; _totalSupply = 2971215073000000000000000000; balances[0xEF6881DCE372fdC99d1932838B024C875e27FBC9] = _totalSupply; emit Transfer(address(0), 0xEF6881DCE372fdC99d1932838B024C875e27FBC9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.5.0+commit.1d4f565a
GNU GPLv3
bzzr://fe03f09da0e82ec9bd31470ae8f46bf71efa12ab68481643cb7cf8d4437d900c
{ "func_code_index": [ 5303, 5492 ] }
58,056
ERC20Token
ERC20Token.sol
0x9611fd98881473d2adadbc49e6567df6192dec29
Solidity
SafeMath
library SafeMath { /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; }
/** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
OSL-3.0
bzzr://74a9a6e00aed31693f8140f1aedf6b445ae60c30769fcc70b6da4aaaf75f1daa
{ "func_code_index": [ 150, 339 ] }
58,057
ERC20Token
ERC20Token.sol
0x9611fd98881473d2adadbc49e6567df6192dec29
Solidity
SafeMath
library SafeMath { /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
/** * @dev Adds two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
OSL-3.0
bzzr://74a9a6e00aed31693f8140f1aedf6b445ae60c30769fcc70b6da4aaaf75f1daa
{ "func_code_index": [ 422, 608 ] }
58,058
ERC20Token
ERC20Token.sol
0x9611fd98881473d2adadbc49e6567df6192dec29
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev Total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev Transfer token to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowances[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowances[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowances[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0), "ERC20: transfer to the zero address"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowances[account][msg.sender].sub(value)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return _totalSupply; }
/** * @dev Total number of tokens in existence. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
OSL-3.0
bzzr://74a9a6e00aed31693f8140f1aedf6b445ae60c30769fcc70b6da4aaaf75f1daa
{ "func_code_index": [ 301, 397 ] }
58,059
ERC20Token
ERC20Token.sol
0x9611fd98881473d2adadbc49e6567df6192dec29
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev Total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev Transfer token to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowances[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowances[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowances[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0), "ERC20: transfer to the zero address"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowances[account][msg.sender].sub(value)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */
NatSpecMultiLine
balanceOf
function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; }
/** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
OSL-3.0
bzzr://74a9a6e00aed31693f8140f1aedf6b445ae60c30769fcc70b6da4aaaf75f1daa
{ "func_code_index": [ 611, 722 ] }
58,060