Transaction Hash:
Block:
12582716 at Jun-06-2021 07:06:39 PM +UTC
Transaction Fee:
0.0047238502 ETH
$12.01
Gas Used:
247,322 Gas / 19.1 Gwei
Emitted Events:
96 |
RebalancingSetToken.Transfer( from=[Sender] 0xd1898665a01a91ac10bd2c6cb1899336df34ac33, to=0x0000000000000000000000000000000000000000, value=640000000000000000 )
|
97 |
Core.SetRedeemed( _setAddress=RebalancingSetToken, _quantity=640000000000000000 )
|
98 |
SetToken.Transfer( from=Vault, to=0x0000000000000000000000000000000000000000, value=87500160000000000 )
|
99 |
Core.SetRedeemed( _setAddress=SetToken, _quantity=87500160000000000 )
|
100 |
WETH9.Transfer( src=Vault, dst=[Receiver] 0xda6786379ff88729264d31d472fa917f5e561443, wad=183501135544320000 )
|
101 |
WETH9.Withdrawal( src=[Receiver] 0xda6786379ff88729264d31d472fa917f5e561443, wad=183501135544320000 )
|
102 |
0xda6786379ff88729264d31d472fa917f5e561443.0x412d6167082ef33d0eb78858a5ca2bc234ae9f96ea4757e6c0e2a66a152c0f62( 0x412d6167082ef33d0eb78858a5ca2bc234ae9f96ea4757e6c0e2a66a152c0f62, 0x0000000000000000000000008933ea1ce67b946bdf2436ce860ffbb53ce814d2, 0x000000000000000000000000d1898665a01a91ac10bd2c6cb1899336df34ac33, 00000000000000000000000000000000000000000000000008e1bc9bf0400000 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x311d77dd...a7eBc982c | |||||
0x5B67871C...670D986Dc | (Set: Vault) | ||||
0x8933ea1C...53Ce814d2 | |||||
0x99C85bb6...993Cb89E3
Miner
| (BeePool) | 1,969.858073954457691814 Eth | 1,969.862797804657691814 Eth | 0.0047238502 | |
0xC02aaA39...83C756Cc2 | 6,285,626.978580306570576768 Eth | 6,285,626.795079171026256768 Eth | 0.18350113554432 | ||
0xD1898665...6df34AC33 |
0.230353799516570414 Eth
Nonce: 298
|
0.409131084860890414 Eth
Nonce: 299
| 0.17877728534432 | ||
0xDA678637...f5E561443 | |||||
0xf55186CC...427a120C8 |
Execution Trace
Set: Rebalancing Set Issuance Module V2.f7b00c9e( )

-
RebalancingSetToken.STATICCALL( )
-
SetToken.tokenIsComponent( _tokenAddress=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( True )
-
Core.validSets( _set=0x8933ea1Ce67B946BdF2436cE860fFBb53Ce814d2 ) => ( True )
-
RebalancingSetToken.STATICCALL( )
Core.redeemModule( _burnAddress=0xD1898665a01A91AC10bD2C6cb1899336df34AC33, _incrementAddress=0xDA6786379FF88729264d31d472FA917f5E561443, _set=0x8933ea1Ce67B946BdF2436cE860fFBb53Ce814d2, _quantity=640000000000000000 )
0xdc733ec262f32882f7c05525cc2d09f2c04d86ac.49468457( )
-
RebalancingSetToken.STATICCALL( )
-
-
RebalancingSetToken.burn( _from=0xD1898665a01A91AC10bD2C6cb1899336df34AC33, _quantity=640000000000000000 )
-
RebalancingSetToken.STATICCALL( )
-
RebalancingSetToken.STATICCALL( )
-
RebalancingSetToken.STATICCALL( )
-
CoreIssuanceLibrary.calculateRequiredComponentQuantities( _componentUnits=[136719], _naturalUnit=1000000, _quantity=640000000000000000 ) => ( [87500160000000000] )
-
Vault.batchDecrementTokenOwner( _tokens=[0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c], _owner=0x8933ea1Ce67B946BdF2436cE860fFBb53Ce814d2, _quantities=[87500160000000000] )
-
RebalancingSetToken.STATICCALL( )
-
Vault.batchIncrementTokenOwner( _tokens=[0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c], _owner=0xDA6786379FF88729264d31d472FA917f5E561443, _quantities=[87500160000000000] )
-
SetToken.STATICCALL( )
-
Vault.getOwnerBalance( _token=0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c, _owner=0xDA6786379FF88729264d31d472FA917f5E561443 ) => ( 87500160000000000 )
Core.redeemInVault( _set=0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c, _quantity=87500160000000000 )
-
Vault.decrementTokenOwner( _token=0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c, _owner=0xDA6786379FF88729264d31d472FA917f5E561443, _quantity=87500160000000000 )
0xdc733ec262f32882f7c05525cc2d09f2c04d86ac.49468457( )
-
SetToken.STATICCALL( )
-
SetToken.burn( _from=0x5B67871C3a857dE81A1ca0f9F7945e5670D986Dc, _quantity=87500160000000000 )
-
SetTokenFactory.CALL( )
-
-
SetToken.STATICCALL( )
-
SetToken.STATICCALL( )
-
SetToken.STATICCALL( )
-
CoreIssuanceLibrary.calculateRequiredComponentQuantities( _componentUnits=[2097152], _naturalUnit=1000000, _quantity=87500160000000000 ) => ( [183501135544320000] )
-
Vault.batchDecrementTokenOwner( _tokens=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], _owner=0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c, _quantities=[183501135544320000] )
-
SetToken.STATICCALL( )
-
Vault.batchIncrementTokenOwner( _tokens=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], _owner=0xDA6786379FF88729264d31d472FA917f5E561443, _quantities=[183501135544320000] )
-
-
SetToken.STATICCALL( )
-
Vault.getOwnerBalance( _token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, _owner=0xDA6786379FF88729264d31d472FA917f5E561443 ) => ( 183501135544320000 )
-
AddressToAddressWhiteList.whitelist( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 0x0000000000000000000000000000000000000000 )
Core.withdrawModule( _from=0xDA6786379FF88729264d31d472FA917f5E561443, _to=0xDA6786379FF88729264d31d472FA917f5E561443, _token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, _quantity=183501135544320000 )
-
CommonValidationsLibrary.validateNonEmpty( _addressArray=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2] )
-
CommonValidationsLibrary.validateEqualLength( _addressArray=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], _uint256Array=[183501135544320000] )
-
Vault.batchDecrementTokenOwner( _tokens=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], _owner=0xDA6786379FF88729264d31d472FA917f5E561443, _quantities=[183501135544320000] )
Vault.batchWithdrawTo( _tokens=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], _to=0xDA6786379FF88729264d31d472FA917f5E561443, _quantities=[183501135544320000] )
ERC20Wrapper.balanceOf( _token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, _owner=0x5B67871C3a857dE81A1ca0f9F7945e5670D986Dc ) => ( 4037314981986815624114 )
-
WETH9.balanceOf( 0x5B67871C3a857dE81A1ca0f9F7945e5670D986Dc ) => ( 4037314981986815624114 )
-
ERC20Wrapper.beabacc8( )
-
WETH9.transfer( dst=0xDA6786379FF88729264d31d472FA917f5E561443, wad=183501135544320000 ) => ( True )
-
ERC20Wrapper.balanceOf( _token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, _owner=0x5B67871C3a857dE81A1ca0f9F7945e5670D986Dc ) => ( 4037131480851271304114 )
-
WETH9.balanceOf( 0x5B67871C3a857dE81A1ca0f9F7945e5670D986Dc ) => ( 4037131480851271304114 )
-
-
WETH9.withdraw( wad=183501135544320000 )
- ETH 0.18350113554432
Set: Rebalancing Set Issuance Module V2.CALL( )
- ETH 0.18350113554432
- ETH 0.18350113554432
0xd1898665a01a91ac10bd2c6cb1899336df34ac33.CALL( )
ERC20Wrapper.balanceOf( _token=0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c, _owner=0xDA6786379FF88729264d31d472FA917f5E561443 ) => ( 0 )
-
SetToken.balanceOf( owner=0xDA6786379FF88729264d31d472FA917f5E561443 ) => ( 0 )
-
-
Vault.getOwnerBalance( _token=0x311d77ddeA3c5B187b31b9c588fA508a7eBc982c, _owner=0xDA6786379FF88729264d31d472FA917f5E561443 ) => ( 0 )
File 1 of 10: RebalancingSetToken
File 2 of 10: Core
File 3 of 10: Vault
File 4 of 10: SetToken
File 5 of 10: WETH9
File 6 of 10: CoreIssuanceLibrary
File 7 of 10: SetTokenFactory
File 8 of 10: AddressToAddressWhiteList
File 9 of 10: CommonValidationsLibrary
File 10 of 10: ERC20Wrapper
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; pragma experimental "ABIEncoderV2"; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @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. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; 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 _allowed[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, _allowed[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 _allowed[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, _allowed[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 _allowed[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, _allowed[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)); _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)); _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)); _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(spender != address(0)); require(owner != address(0)); _allowed[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, _allowed[account][msg.sender].sub(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/core/interfaces/ICore.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICore * @author Set Protocol * * The ICore Contract defines all the functions exposed in the Core through its * various extensions and is a light weight way to interact with the contract. */ interface ICore { /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address); /** * Return vault address. * * @return address vault address */ function vault() external view returns (address); /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address); /* * Returns if valid set * * @return bool Returns true if Set created through Core and isn't disabled */ function validSets(address) external view returns (bool); /* * Returns if valid module * * @return bool Returns true if valid module */ function validModules(address) external view returns (bool); /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool); /** * Exchanges components for Set Tokens * * @param _set Address of set to issue * @param _quantity Quantity of set to issue */ function issue( address _set, uint256 _quantity ) external; /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external; /** * Converts user's components into Set Tokens held directly in Vault instead of user's account * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeem( address _set, uint256 _quantity ) external; /** * Redeem Set token and return components to specified recipient. The components * are left in the vault * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens held in vault into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeemInVault( address _set, uint256 _quantity ) external; /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external; /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Deposit any quantity of tokens into the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external; /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external; /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external; /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); /** * Exposes internal function that deposits a quantity of tokens to the vault and attributes * the tokens respectively, to system modules. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that withdraws a quantity of tokens from the vault and * deattributes the tokens respectively, to system modules. * * @param _from Address to decredit for withdraw * @param _to Address to transfer tokens to * @param _token Address of token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that deposits multiple tokens to the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _owner, address _recipient, address _set, uint256 _quantity ) external; /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external; /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external; /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/interfaces/IWhiteList.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IWhiteList * @author Set Protocol * * The IWhiteList interface exposes the whitelist mapping to check components */ interface IWhiteList { /* ============ External Functions ============ */ /** * Validates address against white list * * @param _address Address to check * @return bool Whether passed in address is whitelisted */ function whiteList( address _address ) external view returns (bool); /** * Verifies an array of addresses against the whitelist * * @param _addresses Array of addresses to verify * @return bool Whether all addresses in the list are whitelsited */ function areValidAddresses( address[] calldata _addresses ) external view returns (bool); } // File: contracts/core/interfaces/IRebalancingSetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IRebalancingSetFactory * @author Set Protocol * * The IRebalancingSetFactory interface provides operability for authorized contracts * to interact with RebalancingSetTokenFactory */ contract IRebalancingSetFactory is ISetFactory { /** * Getter for minimumRebalanceInterval of RebalancingSetTokenFactory, used * to enforce rebalanceInterval when creating a RebalancingSetToken * * @return uint256 Minimum amount of time between rebalances in seconds */ function minimumRebalanceInterval() external returns (uint256); /** * Getter for minimumProposalPeriod of RebalancingSetTokenFactory, used * to enforce proposalPeriod when creating a RebalancingSetToken * * @return uint256 Minimum amount of time users can review proposals in seconds */ function minimumProposalPeriod() external returns (uint256); /** * Getter for minimumTimeToPivot of RebalancingSetTokenFactory, used * to enforce auctionTimeToPivot when proposing a rebalance * * @return uint256 Minimum amount of time before auction pivot reached */ function minimumTimeToPivot() external returns (uint256); /** * Getter for maximumTimeToPivot of RebalancingSetTokenFactory, used * to enforce auctionTimeToPivot when proposing a rebalance * * @return uint256 Maximum amount of time before auction pivot reached */ function maximumTimeToPivot() external returns (uint256); /** * Getter for minimumNaturalUnit of RebalancingSetTokenFactory * * @return uint256 Minimum natural unit */ function minimumNaturalUnit() external returns (uint256); /** * Getter for maximumNaturalUnit of RebalancingSetTokenFactory * * @return uint256 Maximum Minimum natural unit */ function maximumNaturalUnit() external returns (uint256); /** * Getter for rebalanceAuctionModule address on RebalancingSetTokenFactory * * @return address Address of rebalanceAuctionModule */ function rebalanceAuctionModule() external returns (address); } // File: contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * 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 ) external; } // File: contracts/core/interfaces/IVault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IVault * @author Set Protocol * * The IVault interface provides a light-weight, structured way to interact with the Vault * contract from another contract. */ interface IVault { /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) external; /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) external; /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external; /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256); } // File: contracts/core/lib/RebalancingLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingLibrary * @author Set Protocol * * The RebalancingLibrary contains functions for facilitating the rebalancing process for * Rebalancing Set Tokens. Removes the old calculation functions * */ library RebalancingLibrary { /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance, Drawdown } /* ============ Structs ============ */ struct AuctionPriceParameters { uint256 auctionStartTime; uint256 auctionTimeToPivot; uint256 auctionStartPrice; uint256 auctionPivotPrice; } struct BiddingParameters { uint256 minimumBid; uint256 remainingCurrentSets; uint256[] combinedCurrentUnits; uint256[] combinedNextSetUnits; address[] combinedTokenArray; } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/core/tokens/rebalancing-libraries/FailAuctionLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title FailAuctionLibrary * @author Set Protocol * * Default implementation of Rebalancing Set Token endFailedAuction function */ library FailAuctionLibrary { using SafeMath for uint256; /** * Fail an auction that doesn't complete before reaching the pivot price. Move to Drawdown state * if bids have been placed. Reset to Default state if no bids placed. * * @param _startingCurrentSetAmount Amount of current set at beginning or rebalance * @param _calculatedUnitShares Calculated unitShares amount if rebalance were to be settled * @param _currentSet The Set that failed to rebalance * @param _coreAddress Core address * @param _auctionPriceParameters Struct containing auction price curve parameters * @param _biddingParameters Struct containing relevant data for calculating token flows * @param _rebalanceState State rebalancing set token is in * @return State of Rebalancing Set after function called */ function endFailedAuction( uint256 _startingCurrentSetAmount, uint256 _calculatedUnitShares, address _currentSet, address _coreAddress, RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters, RebalancingLibrary.BiddingParameters memory _biddingParameters, uint8 _rebalanceState ) public returns (uint8) { // Token must be in Rebalance State require( _rebalanceState == uint8(RebalancingLibrary.State.Rebalance), "RebalanceAuctionModule.endFailedAuction: Rebalancing Set Token must be in Rebalance State" ); // Calculate timestamp when pivot is reached uint256 revertAuctionTime = _auctionPriceParameters.auctionStartTime.add( _auctionPriceParameters.auctionTimeToPivot ); // Make sure auction has gone past pivot point require( block.timestamp >= revertAuctionTime, "RebalanceAuctionModule.endFailedAuction: Can only be called after auction reaches pivot" ); uint8 newRebalanceState; /** * If not enough sets have been bid on then allow auction to fail where no bids being registered * returns the rebalancing set token to pre-auction state and some bids being registered puts the * rebalancing set token in Drawdown mode. * * However, if enough sets have been bid on. Then allow auction to fail and enter Drawdown state if * and only if the calculated post-auction unitShares is equal to 0. */ if (_biddingParameters.remainingCurrentSets >= _biddingParameters.minimumBid) { // Check if any bids have been placed if (_startingCurrentSetAmount == _biddingParameters.remainingCurrentSets) { // If bid not placed, reissue current Set ICore(_coreAddress).issueInVault( _currentSet, _startingCurrentSetAmount ); // Set Rebalance Set Token state to Default newRebalanceState = uint8(RebalancingLibrary.State.Default); } else { // Set Rebalancing Set Token to Drawdown state newRebalanceState = uint8(RebalancingLibrary.State.Drawdown); } } else { // If settleRebalance can be called then endFailedAuction can't be unless calculatedUnitShares // equals 0 require( _calculatedUnitShares == 0, "RebalancingSetToken.endFailedAuction: Cannot be called if rebalance is viably completed" ); // If calculated unitShares equals 0 set to Drawdown state newRebalanceState = uint8(RebalancingLibrary.State.Drawdown); } return newRebalanceState; } } // File: contracts/core/lib/auction-price-libraries/IAuctionPriceCurve.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IAuctionPriceCurve * @author Set Protocol * * The IAuctionPriceCurve interface provides a structured way to interact with any AuctionLibrary */ interface IAuctionPriceCurve { /* * Getter for priceDivisor variable on Auction Price Curve Library */ function priceDivisor() external view returns (uint256); /* * Validate any auction parameters that have library-specific restrictions * * @param _auctionPriceParameters Struct containing relevant auction price parameters */ function validateAuctionPriceParameters( RebalancingLibrary.AuctionPriceParameters calldata _auctionPriceParameters ) external view; /* * Calculate the current priceRatio for an auction given defined price and time parameters * * @param _auctionPriceParameters Struct containing relevant auction price parameters * @return uint256 The auction price numerator * @return uint256 The auction price denominator */ function getCurrentPrice( RebalancingLibrary.AuctionPriceParameters calldata _auctionPriceParameters ) external view returns (uint256, uint256); } // File: contracts/core/tokens/rebalancing-libraries/PlaceBidLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title PlaceBidLibrary * @author Set Protocol * * Default implementation of Rebalancing Set Token placeBid function */ library PlaceBidLibrary { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @param _coreAddress Core address * @param _biddingParameters Struct containing relevant data for calculating token flows * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function validatePlaceBid( uint256 _quantity, address _coreAddress, RebalancingLibrary.BiddingParameters memory _biddingParameters ) public view returns (uint256) { // Make sure sender is a module require( ICore(_coreAddress).validModules(msg.sender), "RebalancingSetToken.placeBid: Sender must be approved module" ); // Make sure that bid amount is greater than zero require( _quantity > 0, "RebalancingSetToken.placeBid: Bid must be > 0" ); // Make sure that bid amount is multiple of minimum bid amount require( _quantity.mod(_biddingParameters.minimumBid) == 0, "RebalancingSetToken.placeBid: Must bid multiple of minimum bid" ); // Make sure that bid Amount is less than remainingCurrentSets require( _quantity <= _biddingParameters.remainingCurrentSets, "RebalancingSetToken.placeBid: Bid exceeds remaining current sets" ); } /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @param _auctionLibrary Auction library used in rebalance * @param _biddingParameters Struct containing relevant data for calculating token flows * @param _auctionPriceParameters Struct containing auction price curve parameters * @param _rebalanceState State of rebalancing set token * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity, address _auctionLibrary, RebalancingLibrary.BiddingParameters memory _biddingParameters, RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters, uint8 _rebalanceState ) public view returns (uint256[] memory, uint256[] memory) { // Confirm in Rebalance State require( _rebalanceState == uint8(RebalancingLibrary.State.Rebalance), "RebalancingSetToken.getBidPrice: State must be Rebalance" ); // Get bid conversion price, currently static placeholder for calling auctionlibrary uint256 priceNumerator; uint256 priceDivisor; (priceNumerator, priceDivisor) = IAuctionPriceCurve(_auctionLibrary).getCurrentPrice( _auctionPriceParameters ); // Normalized quantity amount uint256 unitsMultiplier = _quantity.div(_biddingParameters.minimumBid).mul(priceDivisor); // Calculate token flow arrays return createTokenFlowArrays( unitsMultiplier, priceNumerator, priceDivisor, _biddingParameters ); } /* * Creates arrays of token inflows and outflows * * @param _unitsMultiplier Bid amount normalized to number of standard bid amounts * @param _priceNumerator The numerator of the price ratio * @param _priceDivisor The denominator of the price ratio * @param _biddingParameters Struct containing relevant data for calculating token flows * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function createTokenFlowArrays( uint256 _unitsMultiplier, uint256 _priceNumerator, uint256 _priceDivisor, RebalancingLibrary.BiddingParameters memory _biddingParameters ) public pure returns (uint256[] memory, uint256[] memory) { // Declare unit arrays in memory uint256 combinedTokenCount = _biddingParameters.combinedTokenArray.length; uint256[] memory inflowUnitArray = new uint256[](combinedTokenCount); uint256[] memory outflowUnitArray = new uint256[](combinedTokenCount); // Cycle through each token in combinedTokenArray, calculate inflow/outflow and store // result in array for (uint256 i = 0; i < combinedTokenCount; i++) { ( inflowUnitArray[i], outflowUnitArray[i] ) = calculateTokenFlows( _biddingParameters.combinedCurrentUnits[i], _biddingParameters.combinedNextSetUnits[i], _unitsMultiplier, _priceNumerator, _priceDivisor ); } return (inflowUnitArray, outflowUnitArray); } /* * Calculates token inflow/outflow for single component in combinedTokenArray * * @param _currentUnit Amount of token i in currentSet per minimum bid amount * @param _nextSetUnit Amount of token i in nextSet per minimum bid amount * @param _unitsMultiplier Bid amount normalized to number of minimum bid amounts * @param _priceNumerator The numerator of the price ratio * @param _priceDivisor The denominator of the price ratio * @return inflowUnit Amount of token i transferred into the system * @return outflowUnit Amount of token i transferred to the bidder */ function calculateTokenFlows( uint256 _currentUnit, uint256 _nextSetUnit, uint256 _unitsMultiplier, uint256 _priceNumerator, uint256 _priceDivisor ) public pure returns (uint256, uint256) { /* * Below is a mathematically simplified formula for calculating token inflows and * outflows, the following is it's derivation: * token_flow = (bidQuantity/price)*(nextUnit - price*currentUnit) * * Where, * 1) price = (priceNumerator/priceDivisor), * 2) nextUnit and currentUnit are the amount of component i needed for a * standardAmount of sets to be rebalanced where one standardAmount = * max(natural unit nextSet, natural unit currentSet), and * 3) bidQuantity is a normalized amount in terms of the standardAmount used * to calculate nextUnit and currentUnit. This is represented by the unitsMultiplier * variable. * * Given these definitions we can derive the below formula as follows: * token_flow = (unitsMultiplier/(priceNumerator/priceDivisor))* * (nextUnit - (priceNumerator/priceDivisor)*currentUnit) * * We can then multiply this equation by (priceDivisor/priceDivisor) * which simplifies the above equation to: * * (unitsMultiplier/priceNumerator)* (nextUnit*priceDivisor - currentUnit*priceNumerator) * * This is the equation seen below, but since unsigned integers are used we must check to see if * nextUnit*priceDivisor > currentUnit*priceNumerator, otherwise those two terms must be * flipped in the equation. */ uint256 inflowUnit; uint256 outflowUnit; // Use if statement to check if token inflow or outflow if (_nextSetUnit.mul(_priceDivisor) > _currentUnit.mul(_priceNumerator)) { // Calculate inflow amount inflowUnit = _unitsMultiplier.mul( _nextSetUnit.mul(_priceDivisor).sub(_currentUnit.mul(_priceNumerator)) ).div(_priceNumerator); // Set outflow amount to 0 for component i, since tokens need to be injected in rebalance outflowUnit = 0; } else { // Calculate outflow amount outflowUnit = _unitsMultiplier.mul( _currentUnit.mul(_priceNumerator).sub(_nextSetUnit.mul(_priceDivisor)) ).div(_priceNumerator); // Set inflow amount to 0 for component i, since tokens need to be returned in rebalance inflowUnit = 0; } return (inflowUnit, outflowUnit); } } // File: contracts/core/tokens/rebalancing-libraries/ProposeLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ProposeLibrary * @author Set Protocol * * Default implementation of Rebalancing Set Token propose function */ library ProposeLibrary { using SafeMath for uint256; /* ============ Structs ============ */ struct ProposalContext { address manager; address currentSet; address coreAddress; address componentWhitelist; address factoryAddress; uint256 lastRebalanceTimestamp; uint256 rebalanceInterval; uint8 rebalanceState; } /* ============ Internal Functions ============ */ /** * Function used to validate inputs to propose function * * @param _nextSet The Set to rebalance into * @param _auctionLibrary The library used to calculate the Dutch Auction price * @param _proposalContext Rebalancing Set Token state parameters needed for proposal validation */ function validateProposal( address _nextSet, address _auctionLibrary, ProposalContext memory _proposalContext, RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters ) public { ICore coreInstance = ICore(_proposalContext.coreAddress); IRebalancingSetFactory factoryInstance = IRebalancingSetFactory(_proposalContext.factoryAddress); // Make sure it is manager that is proposing the rebalance require( msg.sender == _proposalContext.manager, "ProposeLibrary.validateProposal: Sender must be manager" ); // New Proposal can only be made in Default and Proposal state require( _proposalContext.rebalanceState == uint8(RebalancingLibrary.State.Default) || _proposalContext.rebalanceState == uint8(RebalancingLibrary.State.Proposal), "ProposeLibrary.validateProposal: State must be in Propose or Default" ); // Make sure enough time has passed from last rebalance to start a new proposal require( block.timestamp >= _proposalContext.lastRebalanceTimestamp.add( _proposalContext.rebalanceInterval ), "ProposeLibrary.validateProposal: Rebalance interval not elapsed" ); // Check that new proposed Set is valid Set created by Core require( coreInstance.validSets(_nextSet), "ProposeLibrary.validateProposal: Invalid or disabled proposed SetToken address" ); // Check proposed components on whitelist. This is to ensure managers are unable to add contract addresses // to a propose that prohibit the set from carrying out an auction i.e. a token that only the manager possesses require( IWhiteList( _proposalContext.componentWhitelist ).areValidAddresses(ISetToken(_nextSet).getComponents()), "ProposeLibrary.validateProposal: Proposed set contains invalid component token" ); // Check that the auction library is a valid priceLibrary tracked by Core require( coreInstance.validPriceLibraries(_auctionLibrary), "ProposeLibrary.validateProposal: Invalid or disabled PriceLibrary address" ); // Check that auctionTimeToPivot is greater than or equal to 6 hours require( _auctionPriceParameters.auctionTimeToPivot >= factoryInstance.minimumTimeToPivot(), "ProposeLibrary.validateProposal: Time to pivot must be greater than minimum" ); // Check that auctionTimeToPivot is less than or equal to 3 days require( _auctionPriceParameters.auctionTimeToPivot <= factoryInstance.maximumTimeToPivot(), "ProposeLibrary.validateProposal: Time to pivot must be greater than maximum" ); // Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa. // Done to make sure that when calculating token units there will are no rounding errors. uint256 currentNaturalUnit = ISetToken(_proposalContext.currentSet).naturalUnit(); uint256 nextSetNaturalUnit = ISetToken(_nextSet).naturalUnit(); require( Math.max(currentNaturalUnit, nextSetNaturalUnit).mod( Math.min(currentNaturalUnit, nextSetNaturalUnit) ) == 0, "ProposeLibrary.validateProposal: Invalid proposed Set natural unit" ); // Check that pivot price is compliant with library restrictions IAuctionPriceCurve(_auctionLibrary).validateAuctionPriceParameters( _auctionPriceParameters ); } } // File: contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/core/tokens/rebalancing-libraries/SettleRebalanceLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title SettleRebalanceLibrary * @author Set Protocol * * Default implementation of Rebalancing Set Token settle rebalance and related functions. */ library SettleRebalanceLibrary { using SafeMath for uint256; /* ============ Internal Functions ============ */ /** * Calculate the amount of nextSets to issue by using the component amounts in the * vault, new unitShares follow from this calculation * * @param _totalSupply Total supply of rebalancing set token * @param _remainingCurrentSets Amount of currentSets remaining * @param _minimumBid Minimum bid allowed, used to see if valid settle * @param _naturalUnit Natural unit of rebalancing set token * @param _nextSet Address of next set * @param _coreAddress Core address * @param _vaultAddress Vault address * @return uint256 Amount of nextSets to issue */ function settleRebalance( uint256 _totalSupply, uint256 _remainingCurrentSets, uint256 _minimumBid, uint256 _naturalUnit, address _nextSet, address _coreAddress, address _vaultAddress, uint8 _rebalanceState ) public returns (uint256) { // Must be in Rebalance state to call settlement require( _rebalanceState == uint8(RebalancingLibrary.State.Rebalance), "RebalancingSetToken.settleRebalance: State must be Rebalance" ); // Make sure all currentSets have been rebalanced require( _remainingCurrentSets < _minimumBid, "RebalancingSetToken.settleRebalance: Rebalance not completed" ); // Calculate next Set quantities uint256 issueAmount; uint256 nextUnitShares; ( issueAmount, nextUnitShares ) = calculateNextSetIssueQuantity( _totalSupply, _naturalUnit, _nextSet, _vaultAddress ); require( nextUnitShares > 0, "RebalancingSetToken.settleRebalance: Failed rebalance, unitshares equals 0. Call endFailedAuction." ); // Issue nextSet to RebalancingSetToken ICore(_coreAddress).issueInVault( _nextSet, issueAmount ); return nextUnitShares; } /** * Calculate the amount of nextSets to issue by using the component amounts in the * vault, unitShares following from this calculation. * * @param _totalSupply Total supply of rebalancing set token * @param _naturalUnit Natural unit of rebalancing set token * @param _nextSet Address of next set * @param _vaultAddress Vault address * @return uint256 Amount of nextSets to issue * @return uint256 New unitShares for the rebalancingSetToken */ function calculateNextSetIssueQuantity( uint256 _totalSupply, uint256 _naturalUnit, address _nextSet, address _vaultAddress ) public view returns (uint256, uint256) { // Collect data necessary to compute issueAmounts SetTokenLibrary.SetDetails memory nextSetToken = SetTokenLibrary.getSetDetails(_nextSet); uint256 maxIssueAmount = calculateMaxIssueAmount( _vaultAddress, nextSetToken ); // Calculate the amount of naturalUnits worth of rebalancingSetToken outstanding uint256 naturalUnitsOutstanding = _totalSupply.div(_naturalUnit); // Issue amount of Sets that is closest multiple of nextNaturalUnit to the maxIssueAmount // Since the initial division will round down to the nearest whole number when we multiply // by that same number we will return the closest multiple less than the maxIssueAmount uint256 issueAmount = maxIssueAmount.div(nextSetToken.naturalUnit).mul(nextSetToken.naturalUnit); // Divide final issueAmount by naturalUnitsOutstanding to get newUnitShares uint256 newUnitShares = issueAmount.div(naturalUnitsOutstanding); return (issueAmount, newUnitShares); } /** * Get the maximum possible issue amount of nextSet based on number of components owned by rebalancing * set token. * * @param _vaultAddress Vault address * @param _setToken nextSet details * @return uint256 maxIssueAmount */ function calculateMaxIssueAmount( address _vaultAddress, SetTokenLibrary.SetDetails memory _setToken ) public view returns (uint256) { uint256 maxIssueAmount = CommonMath.maxUInt256(); IVault vaultInstance = IVault(_vaultAddress); for (uint256 i = 0; i < _setToken.components.length; i++) { // Get amount of components in vault owned by rebalancingSetToken uint256 componentAmount = vaultInstance.getOwnerBalance( _setToken.components[i], address(this) ); // Calculate amount of Sets that can be issued from those components, if less than amount for other // components then set that as maxIssueAmount uint256 componentIssueAmount = componentAmount.div(_setToken.units[i]).mul(_setToken.naturalUnit); if (componentIssueAmount < maxIssueAmount) { maxIssueAmount = componentIssueAmount; } } return maxIssueAmount; } } // File: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /// @return Returns index and isIn for the first occurrence starting from /// end function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = length; i > 0; i--) { if (A[i - 1] == a) { return (i, true); } } return (0, false); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the combination of two storage arrays. * @param A The first array * @param B The second array * @return Returns A appended by a */ function sExtend(address[] storage A, address[] storage B) internal { uint256 length = B.length; for (uint256 i = 0; i < length; i++) { A.push(B[i]); } } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Alternate implementation * Assumes there are no duplicates */ function unionB(address[] memory A, address[] memory B) internal pure returns (address[] memory) { bool[] memory includeMap = new bool[](A.length + B.length); uint256 count = 0; for (uint256 i = 0; i < A.length; i++) { includeMap[i] = true; count++; } for (uint256 j = 0; j < B.length; j++) { if (!contains(A, B[j])) { includeMap[A.length + j] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 k = 0; for (uint256 m = 0; m < A.length; m++) { if (includeMap[m]) { newAddresses[k] = A[m]; k++; } } for (uint256 n = 0; n < B.length; n++) { if (includeMap[A.length + n]) { newAddresses[k] = B[n]; k++; } } return newAddresses; } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * @dev Reverses storage array in place */ function sReverse(address[] storage A) internal { address t; uint256 length = A.length; for (uint256 i = 0; i < length / 2; i++) { t = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = t; } } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } function sPop(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; for (uint256 i = index; i < length - 1; i++) { A[i] = A[i + 1]; } A.length--; return entry; } /** * Deletes address at index and fills the spot with the last address. * Order is not preserved. * @return Returns the removed entry */ function sPopCheap(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; if (index != length - 1) { A[index] = A[length - 1]; delete A[length - 1]; } A.length--; return entry; } /** * Deletes address at index. Works by swapping it with the last address, then deleting. * Order is not preserved * @param A Storage array to remove from */ function sRemoveCheap(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Error: entry not found"); } else { sPopCheap(A, index); return; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } /** * Returns the elements indexed at indexArray. * @param A The array to index * @param indexArray The array to use to index * @return Returns array containing elements indexed at indexArray */ function argGet(address[] memory A, uint256[] memory indexArray) internal pure returns (address[] memory) { address[] memory array = new address[](indexArray.length); for (uint256 i = 0; i < indexArray.length; i++) { array[i] = A[indexArray[i]]; } return array; } } // File: contracts/core/tokens/rebalancing-libraries/StartRebalanceLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title StartRebalanceLibrary * @author Set Protocol * * Default implementation of Rebalancing Set Token startRebalance function */ library StartRebalanceLibrary { using SafeMath for uint256; using AddressArrayUtils for address[]; /* ============ Internal Functions ============ */ /** * Function used to validate time passed to start a rebalance * * @param _proposalStartTime Start time of proposal period * @param _proposalPeriod Required length of proposal period * @param _rebalanceState State rebalancing set token is in */ function validateStartRebalance( uint256 _proposalStartTime, uint256 _proposalPeriod, uint8 _rebalanceState ) external { // Must be in "Proposal" state before going into "Rebalance" state require( _rebalanceState == uint8(RebalancingLibrary.State.Proposal), "RebalancingSetToken.validateStartRebalance: State must be Proposal" ); // Be sure the full proposal period has elapsed require( block.timestamp >= _proposalStartTime.add(_proposalPeriod), "RebalancingSetToken.validateStartRebalance: Proposal period not elapsed" ); } /** * Function used to validate inputs to propose function and initialize biddingParameters struct * * @param _currentSet Address of current Set * @param _nextSet Address of next Set * @param _auctionLibrary Address of auction library being used in rebalance * @param _coreAddress Core address * @param _vaultAddress Vault address * @return Struct containing bidding parameters */ function redeemCurrentSetAndGetBiddingParameters( address _currentSet, address _nextSet, address _auctionLibrary, address _coreAddress, address _vaultAddress ) public returns (RebalancingLibrary.BiddingParameters memory) { // Redeem rounded quantity of current Sets and return redeemed amount of Sets uint256 remainingCurrentSets = redeemCurrentSet( _currentSet, _coreAddress, _vaultAddress ); // Create combined array data structures and calculate minimum bid needed for auction RebalancingLibrary.BiddingParameters memory biddingParameters = setUpBiddingParameters( _currentSet, _nextSet, _auctionLibrary, remainingCurrentSets ); return biddingParameters; } /** * Create struct that holds array representing all components in currentSet and nextSet. * Calcualate unit difference between both sets relative to the largest natural * unit of the two sets. Calculate minimumBid. * * @param _currentSet Address of current Set * @param _nextSet Address of next Set * @param _auctionLibrary Address of auction library being used in rebalance * @param _remainingCurrentSets Quantity of Current Sets redeemed * @return Struct containing bidding parameters */ function setUpBiddingParameters( address _currentSet, address _nextSet, address _auctionLibrary, uint256 _remainingCurrentSets ) public returns (RebalancingLibrary.BiddingParameters memory) { // Get set details for currentSet and nextSet (units, components, natural units) SetTokenLibrary.SetDetails memory currentSet = SetTokenLibrary.getSetDetails(_currentSet); SetTokenLibrary.SetDetails memory nextSet = SetTokenLibrary.getSetDetails(_nextSet); // Create combinedTokenArray address[] memory combinedTokenArray = currentSet.components.union( nextSet.components ); // Calcualate minimumBid uint256 minimumBid = calculateMinimumBid( currentSet.naturalUnit, nextSet.naturalUnit, _auctionLibrary ); // Require remainingCurrentSets to be greater than minimumBid otherwise no bidding would // be allowed require( _remainingCurrentSets >= minimumBid, "RebalancingSetToken.setUpBiddingParameters: Not enough collateral to rebalance" ); // Create memory version of combinedNextSetUnits and combinedCurrentUnits to only make one // call to storage once arrays have been created uint256[] memory combinedCurrentUnits; uint256[] memory combinedNextSetUnits; ( combinedCurrentUnits, combinedNextSetUnits ) = calculateCombinedUnitArrays( currentSet, nextSet, minimumBid, _auctionLibrary, combinedTokenArray ); // Build Bidding Parameters struct and return return RebalancingLibrary.BiddingParameters({ minimumBid: minimumBid, remainingCurrentSets: _remainingCurrentSets, combinedCurrentUnits: combinedCurrentUnits, combinedNextSetUnits: combinedNextSetUnits, combinedTokenArray: combinedTokenArray }); } /** * Calculate the minimumBid allowed for the rebalance * * @param _currentSetNaturalUnit Natural unit of currentSet * @param _nextSetNaturalUnit Natural of nextSet * @param _auctionLibrary Address of auction library being used in rebalance * @return Minimum bid amount */ function calculateMinimumBid( uint256 _currentSetNaturalUnit, uint256 _nextSetNaturalUnit, address _auctionLibrary ) private view returns (uint256) { // Get priceDivisor from auctionLibrary uint256 priceDivisor = IAuctionPriceCurve(_auctionLibrary).priceDivisor(); return Math.max( _currentSetNaturalUnit.mul(priceDivisor), _nextSetNaturalUnit.mul(priceDivisor) ); } /** * Create arrays that represents all components in currentSet and nextSet. * Calcualate unit difference between both sets relative to the largest natural * unit of the two sets. * * @param _currentSet Information on currentSet * @param _nextSet Information on nextSet * @param _minimumBid Minimum bid amount * @param _auctionLibrary Address of auction library being used in rebalance * @param _combinedTokenArray Array of component tokens involved in rebalance * @return Unit inflow/outflow arrays for current and next Set */ function calculateCombinedUnitArrays( SetTokenLibrary.SetDetails memory _currentSet, SetTokenLibrary.SetDetails memory _nextSet, uint256 _minimumBid, address _auctionLibrary, address[] memory _combinedTokenArray ) public returns (uint256[] memory, uint256[] memory) { // Create memory version of combinedNextSetUnits and combinedCurrentUnits to only make one // call to storage once arrays have been created uint256[] memory memoryCombinedCurrentUnits = new uint256[](_combinedTokenArray.length); uint256[] memory memoryCombinedNextSetUnits = new uint256[](_combinedTokenArray.length); for (uint256 i = 0; i < _combinedTokenArray.length; i++) { memoryCombinedCurrentUnits[i] = calculateCombinedUnit( _currentSet, _minimumBid, _auctionLibrary, _combinedTokenArray[i] ); memoryCombinedNextSetUnits[i] = calculateCombinedUnit( _nextSet, _minimumBid, _auctionLibrary, _combinedTokenArray[i] ); } return (memoryCombinedCurrentUnits, memoryCombinedNextSetUnits); } /** * Calculations the unit amount of Token to include in the the combined Set units. * * @param _setToken Information on the SetToken * @param _minimumBid Minimum bid amount * @param _auctionLibrary Address of auction library being used in rebalance * @param _currentComponent Current component in iteration * @return Unit inflow/outflow */ function calculateCombinedUnit( SetTokenLibrary.SetDetails memory _setToken, uint256 _minimumBid, address _auctionLibrary, address _currentComponent ) private returns (uint256) { // Check if component in arrays and get index if it is uint256 indexCurrent; bool isComponent; (indexCurrent, isComponent) = _setToken.components.indexOf(_currentComponent); // Compute unit amounts of token in Set if (isComponent) { return computeTransferValue( _setToken.units[indexCurrent], _setToken.naturalUnit, _minimumBid, _auctionLibrary ); } return 0; } /** * Calculates the maximum redemption quantity and redeems the Set into the vault. * Also updates remainingCurrentSets state variable * * @param _currentSet Address of current Set * @param _coreAddress Core address * @param _vaultAddress Vault address * @return Amount of currentSets remaining */ function redeemCurrentSet( address _currentSet, address _coreAddress, address _vaultAddress ) public returns (uint256) { // Get remainingCurrentSets and make it divisible by currentSet natural unit uint256 currentSetBalance = IVault(_vaultAddress).getOwnerBalance( _currentSet, address(this) ); // Calculates the set's natural unit uint256 currentSetNaturalUnit = ISetToken(_currentSet).naturalUnit(); // Rounds the redemption quantity to a multiple of the current Set natural unit and sets variable uint256 remainingCurrentSets = currentSetBalance.div(currentSetNaturalUnit).mul(currentSetNaturalUnit); ICore(_coreAddress).redeemInVault( _currentSet, remainingCurrentSets ); return remainingCurrentSets; } /** * Function to calculate the transfer value of a component given a standardized bid amount * (minimumBid/priceDivisor) * * @param _unit Units of the component token * @param _naturalUnit Natural unit of the Set token * @param _minimumBid Minimum bid amount * @return uint256 Amount of tokens per standard bid amount (minimumBid/priceDivisor) */ function computeTransferValue( uint256 _unit, uint256 _naturalUnit, uint256 _minimumBid, address _auctionLibrary ) internal returns (uint256) { uint256 priceDivisor = IAuctionPriceCurve(_auctionLibrary).priceDivisor(); return _minimumBid.mul(_unit).div(_naturalUnit).div(priceDivisor); } } // File: contracts/core/tokens/RebalancingSetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetToken * @author Set Protocol * * Implementation of Rebalancing Set token. */ contract RebalancingSetToken is ERC20, ERC20Detailed { using SafeMath for uint256; /* ============ State Variables ============ */ // Dependency variables address public core; address public factory; address public vault; address public componentWhiteListAddress; // Core and Vault instances ICore private coreInstance; IVault private vaultInstance; IWhiteList private componentWhiteListInstance; uint256 public naturalUnit; address public manager; RebalancingLibrary.State public rebalanceState; // State updated after every rebalance address public currentSet; uint256 public unitShares; uint256 public lastRebalanceTimestamp; // State governing rebalance cycle uint256 public proposalPeriod; uint256 public rebalanceInterval; // State to track proposal period uint256 public proposalStartTime; // State needed for auction/rebalance address public nextSet; address public auctionLibrary; uint256 public startingCurrentSetAmount; RebalancingLibrary.AuctionPriceParameters public auctionPriceParameters; RebalancingLibrary.BiddingParameters public biddingParameters; // To be used if token put into Drawdown State address[] public failedAuctionWithdrawComponents; /* ============ Events ============ */ event NewManagerAdded( address newManager, address oldManager ); event RebalanceProposed( address nextSet, address indexed auctionLibrary, uint256 indexed proposalPeriodEndTime ); event RebalanceStarted( address oldSet, address newSet ); /* ============ Constructor ============ */ /** * Constructor function for Rebalancing Set Token * * @param _factory Factory used to create the Rebalancing Set * @param _manager Manager of the Rebalancing Set * @param _initialSet Initial set that collateralizes the Rebalancing set * @param _initialUnitShares Units of currentSet that equals one share * @param _naturalUnit The minimum multiple of Sets that can be issued or redeemed * @param _proposalPeriod Amount of time for users to inspect a rebalance proposal * @param _rebalanceInterval Minimum amount of time between rebalances * @param _componentWhiteList Address of component WhiteList contract * @param _name The name of the new RebalancingSetToken * @param _symbol The symbol of the new RebalancingSetToken */ constructor( address _factory, address _manager, address _initialSet, uint256 _initialUnitShares, uint256 _naturalUnit, uint256 _proposalPeriod, uint256 _rebalanceInterval, address _componentWhiteList, string memory _name, string memory _symbol ) public ERC20Detailed( _name, _symbol, 18 ) { // Require initial unit shares is non-zero require( _initialUnitShares > 0, "RebalancingSetToken.constructor: Unit shares must be positive" ); IRebalancingSetFactory tokenFactory = IRebalancingSetFactory(_factory); require( _naturalUnit >= tokenFactory.minimumNaturalUnit(), "RebalancingSetToken.constructor: Natural Unit too low" ); require( _naturalUnit <= tokenFactory.maximumNaturalUnit(), "RebalancingSetToken.constructor: Natural Unit too large" ); // Require manager address is non-zero require( _manager != address(0), "RebalancingSetToken.constructor: Invalid manager address" ); // Require minimum rebalance interval and proposal period from factory require( _proposalPeriod >= tokenFactory.minimumProposalPeriod(), "RebalancingSetToken.constructor: Proposal period too short" ); require( _rebalanceInterval >= tokenFactory.minimumRebalanceInterval(), "RebalancingSetToken.constructor: Rebalance interval too short" ); core = IRebalancingSetFactory(_factory).core(); coreInstance = ICore(core); vault = coreInstance.vault(); vaultInstance = IVault(vault); componentWhiteListAddress = _componentWhiteList; componentWhiteListInstance = IWhiteList(_componentWhiteList); factory = _factory; manager = _manager; currentSet = _initialSet; unitShares = _initialUnitShares; naturalUnit = _naturalUnit; proposalPeriod = _proposalPeriod; rebalanceInterval = _rebalanceInterval; lastRebalanceTimestamp = block.timestamp; rebalanceState = RebalancingLibrary.State.Default; } /* ============ Public Functions ============ */ /** * Function used to set the terms of the next rebalance and start the proposal period * * @param _nextSet The Set to rebalance into * @param _auctionLibrary The library used to calculate the Dutch Auction price * @param _auctionTimeToPivot The amount of time for the auction to go ffrom start to pivot price * @param _auctionStartPrice The price to start the auction at * @param _auctionPivotPrice The price at which the price curve switches from linear to exponential */ function propose( address _nextSet, address _auctionLibrary, uint256 _auctionTimeToPivot, uint256 _auctionStartPrice, uint256 _auctionPivotPrice ) external { // Put together auction price parameters RebalancingLibrary.AuctionPriceParameters memory auctionPriceParams = RebalancingLibrary.AuctionPriceParameters({ auctionTimeToPivot: _auctionTimeToPivot, auctionStartPrice: _auctionStartPrice, auctionPivotPrice: _auctionPivotPrice, auctionStartTime: 0 }); // Create ProposeAuctionParameters ProposeLibrary.ProposalContext memory proposalContext = ProposeLibrary.ProposalContext({ manager: manager, currentSet: currentSet, coreAddress: core, componentWhitelist: componentWhiteListAddress, factoryAddress: factory, lastRebalanceTimestamp: lastRebalanceTimestamp, rebalanceInterval: rebalanceInterval, rebalanceState: uint8(rebalanceState) }); // Validate proposal inputs and initialize auctionPriceParameters ProposeLibrary.validateProposal( _nextSet, _auctionLibrary, proposalContext, auctionPriceParams ); // Update state parameters auctionPriceParameters = auctionPriceParams; nextSet = _nextSet; auctionLibrary = _auctionLibrary; proposalStartTime = block.timestamp; rebalanceState = RebalancingLibrary.State.Proposal; emit RebalanceProposed( _nextSet, _auctionLibrary, proposalStartTime.add(proposalPeriod) ); } /* * Initiate rebalance for the rebalancing set if the proposal period has elapsed after * a proposal. */ function startRebalance() external { // Validate the correct rebalance state and time elapsed StartRebalanceLibrary.validateStartRebalance( proposalStartTime, proposalPeriod, uint8(rebalanceState) ); // Redeem currentSet and set up biddingParameters biddingParameters = StartRebalanceLibrary.redeemCurrentSetAndGetBiddingParameters( currentSet, nextSet, auctionLibrary, core, vault ); // Update state parameters startingCurrentSetAmount = biddingParameters.remainingCurrentSets; auctionPriceParameters.auctionStartTime = block.timestamp; rebalanceState = RebalancingLibrary.State.Rebalance; emit RebalanceStarted(currentSet, nextSet); } /* * Initiate settlement for the rebalancing set. Full functionality now returned to * set owners * */ function settleRebalance() external { // Settle the rebalance and mint next Sets unitShares = SettleRebalanceLibrary.settleRebalance( totalSupply(), biddingParameters.remainingCurrentSets, biddingParameters.minimumBid, naturalUnit, nextSet, core, vault, uint8(rebalanceState) ); // Update other state parameters currentSet = nextSet; lastRebalanceTimestamp = block.timestamp; rebalanceState = RebalancingLibrary.State.Default; clearAuctionState(); } /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory) { // Validate bid quantity and module is sender PlaceBidLibrary.validatePlaceBid( _quantity, core, biddingParameters ); // Place bid and get back inflow and outflow arrays uint256[] memory inflowUnitArray; uint256[] memory outflowUnitArray; ( inflowUnitArray, outflowUnitArray ) = getBidPrice(_quantity); // Update remainingCurrentSet figure to account for placed bid biddingParameters.remainingCurrentSets = biddingParameters.remainingCurrentSets.sub(_quantity); return (biddingParameters.combinedTokenArray, inflowUnitArray, outflowUnitArray); } /* * Fail an auction that doesn't complete before reaching the pivot price. Move to Drawdown state * if bids have been placed. Reset to Default state if no bids placed. * */ function endFailedAuction() external { uint256 calculatedUnitShares; ( , calculatedUnitShares ) = SettleRebalanceLibrary.calculateNextSetIssueQuantity( totalSupply(), naturalUnit, nextSet, vault ); // Fail auction and either reset to Default state or kill Rebalancing Set Token and enter Drawdown // state uint8 integerRebalanceState = FailAuctionLibrary.endFailedAuction( startingCurrentSetAmount, calculatedUnitShares, currentSet, core, auctionPriceParameters, biddingParameters, uint8(rebalanceState) ); rebalanceState = RebalancingLibrary.State(integerRebalanceState); // Reset lastRebalanceTimestamp to now lastRebalanceTimestamp = block.timestamp; // Save combined token arrays to failedAuctionWithdrawComponents failedAuctionWithdrawComponents = biddingParameters.combinedTokenArray; // Clear auction state clearAuctionState(); } /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) public view returns (uint256[] memory, uint256[] memory) { return PlaceBidLibrary.getBidPrice( _quantity, auctionLibrary, biddingParameters, auctionPriceParameters, uint8(rebalanceState) ); } /* * Mint set token for given address. * Can only be called by Core contract. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external { // Check that function caller is Core require( msg.sender == core, "RebalancingSetToken.mint: Sender must be core" ); // Check that set is not in Rebalance State require( rebalanceState != RebalancingLibrary.State.Rebalance, "RebalancingSetToken.mint: Cannot mint during Rebalance" ); // Check that set is not in Drawdown State require( rebalanceState != RebalancingLibrary.State.Drawdown, "RebalancingSetToken.mint: Cannot mint during Drawdown" ); // Update token balance of the manager _mint(_issuer, _quantity); } /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external { // Check that set is not in Rebalancing State require( rebalanceState != RebalancingLibrary.State.Rebalance, "RebalancingSetToken.burn: Cannot burn during Rebalance" ); // Check to see if state is Drawdown if (rebalanceState == RebalancingLibrary.State.Drawdown) { // In Drawdown Sets can only be burned as part of the withdrawal process require( coreInstance.validModules(msg.sender), "RebalancingSetToken.burn: Set cannot be redeemed during Drawdown" ); } else { // When in non-Rebalance or Drawdown state, check that function caller is Core // so that Sets can be redeemed require( msg.sender == core, "RebalancingSetToken.burn: Sender must be core" ); } _burn(_from, _quantity); } /* * Set new manager address * * @param _newManager The address of the new manager account */ function setManager( address _newManager ) external { require( msg.sender == manager, "RebalancingSetToken.setManager: Sender must be the manager" ); emit NewManagerAdded(_newManager, manager); manager = _newManager; } /* ============ Getter Functions ============ */ /* * Get addresses of setToken underlying the Rebalancing Set * * @return componentAddresses Array of currentSet */ function getComponents() external view returns (address[] memory) { address[] memory components = new address[](1); components[0] = currentSet; return components; } /* * Get unitShares of Rebalancing Set * * @return units Array of component unit */ function getUnits() external view returns (uint256[] memory) { uint256[] memory units = new uint256[](1); units[0] = unitShares; return units; } /* * Get biddingParameters of Rebalancing Set * * @return biddingParams Object with bidding information */ function getBiddingParameters() external view returns (uint256[] memory) { uint256[] memory biddingParams = new uint256[](2); biddingParams[0] = biddingParameters.minimumBid; biddingParams[1] = biddingParameters.remainingCurrentSets; return biddingParams; } /* * Get auctionPriceParameters of Rebalancing Set * * @return auctionParams Object with auction information */ function getAuctionPriceParameters() external view returns (uint256[] memory) { uint256[] memory auctionParams = new uint256[](4); auctionParams[0] = auctionPriceParameters.auctionStartTime; auctionParams[1] = auctionPriceParameters.auctionTimeToPivot; auctionParams[2] = auctionPriceParameters.auctionStartPrice; auctionParams[3] = auctionPriceParameters.auctionPivotPrice; return auctionParams; } /* * Checks to make sure address is the current set of the RebalancingSetToken. * Conforms to the ISetToken Interface. * * @param _tokenAddress Address of token being checked * @return bool True if token is the current Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool) { return _tokenAddress == currentSet; } /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArrayLength() external view returns (uint256) { return biddingParameters.combinedTokenArray.length; } /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArray() external view returns (address[] memory) { return biddingParameters.combinedTokenArray; } /* * Get combinedCurrentUnits of Rebalancing Set * * @return combinedCurrentUnits */ function getCombinedCurrentUnits() external view returns (uint256[] memory) { return biddingParameters.combinedCurrentUnits; } /* * Get combinedNextSetUnits of Rebalancing Set * * @return combinedNextSetUnits */ function getCombinedNextSetUnits() external view returns (uint256[] memory) { return biddingParameters.combinedNextSetUnits; } /* * Get failedAuctionWithdrawComponents of Rebalancing Set * * @return failedAuctionWithdrawComponents */ function getFailedAuctionWithdrawComponents() external view returns (address[] memory) { return failedAuctionWithdrawComponents; } /* ============ Internal Functions ============ */ /* * Reset auction specific state after failed or successful rebalance */ function clearAuctionState() internal { nextSet = address(0); auctionLibrary = address(0); startingCurrentSetAmount = 0; delete auctionPriceParameters; delete biddingParameters; } }
File 2 of 10: Core
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.2; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/lib/CommonValidationsLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonValidationsLibrary { /** * Ensures that an address array is not empty. * * @param _addressArray Address array input */ function validateNonEmpty( address[] calldata _addressArray ) external pure { require( _addressArray.length > 0, "Address array length must be > 0" ); } /** * Ensures that an address array and uint256 array are equal length * * @param _addressArray Address array input * @param _uint256Array Uint256 array input */ function validateEqualLength( address[] calldata _addressArray, uint256[] calldata _uint256Array ) external pure { require( _addressArray.length == _uint256Array.length, "Input length mismatch" ); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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; } } // File: contracts/core/interfaces/ITransferProxy.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ITransferProxy * @author Set Protocol * * The ITransferProxy interface provides a light-weight, structured way to interact with the * TransferProxy contract from another contract. */ interface ITransferProxy { /* ============ External Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the proxy). * Can only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transfer( address _token, uint256 _quantity, address _from, address _to ) external; /** * Transfers tokens from an address (that has set allowance on the proxy). * Can only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransfer( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/interfaces/IVault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IVault * @author Set Protocol * * The IVault interface provides a light-weight, structured way to interact with the Vault * contract from another contract. */ interface IVault { /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) external; /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) external; /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external; /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256); } // File: contracts/core/lib/CoreState.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreState * @author Set Protocol * * The CoreState library maintains all state for the Core contract thus * allowing it to operate across multiple mixins. */ contract CoreState { /* ============ Structs ============ */ struct State { // Protocol state of operation uint8 operationState; // Address of the TransferProxy contract address transferProxy; // Address of the Vault contract address vault; // Instance of transferProxy contract ITransferProxy transferProxyInstance; // Instance of Vault Contract IVault vaultInstance; // Mapping of exchange enumeration to address mapping(uint8 => address) exchangeIds; // Mapping of approved modules mapping(address => bool) validModules; // Mapping of tracked SetToken factories mapping(address => bool) validFactories; // Mapping of tracked rebalancing price libraries mapping(address => bool) validPriceLibraries; // Mapping of tracked SetTokens mapping(address => bool) validSets; // Mapping of tracked disabled SetTokens mapping(address => bool) disabledSets; // Array of tracked SetTokens address[] setTokens; // Array of tracked modules address[] modules; // Array of tracked factories address[] factories; // Array of tracked exchange wrappers address[] exchanges; // Array of tracked auction price libraries address[] priceLibraries; } /* ============ State Variables ============ */ State public state; /* ============ Public Getters ============ */ /** * Return uint8 representing the operational state of the protocol * * @return uint8 Uint8 representing the operational state of the protocol */ function operationState() external view returns (uint8) { return state.operationState; } /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address) { return state.exchangeIds[_exchangeId]; } /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address) { return state.transferProxy; } /** * Return vault address * * @return address vault address */ function vault() external view returns (address) { return state.vault; } /** * Return boolean indicating if address is valid factory. * * @param _factory Factory address * @return bool Boolean indicating if enabled factory */ function validFactories( address _factory ) external view returns (bool) { return state.validFactories[_factory]; } /** * Return boolean indicating if address is valid module. * * @param _module Factory address * @return bool Boolean indicating if enabled factory */ function validModules( address _module ) external view returns (bool) { return state.validModules[_module]; } /** * Return boolean indicating if address is valid Set. * * @param _set Set address * @return bool Boolean indicating if valid Set */ function validSets( address _set ) external view returns (bool) { return state.validSets[_set]; } /** * Return boolean indicating if address is a disabled Set. * * @param _set Set address * @return bool Boolean indicating if is a disabled Set */ function disabledSets( address _set ) external view returns (bool) { return state.disabledSets[_set]; } /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool) { return state.validPriceLibraries[_priceLibrary]; } /** * Return array of all valid Set Tokens. * * @return address[] Array of valid Set Tokens */ function setTokens() external view returns (address[] memory) { return state.setTokens; } /** * Return array of all valid Modules. * * @return address[] Array of valid modules */ function modules() external view returns (address[] memory) { return state.modules; } /** * Return array of all valid factories. * * @return address[] Array of valid factories */ function factories() external view returns (address[] memory) { return state.factories; } /** * Return array of all valid exchange wrappers. * * @return address[] Array of valid exchange wrappers */ function exchanges() external view returns (address[] memory) { return state.exchanges; } /** * Return array of all valid price libraries. * * @return address[] Array of valid price libraries */ function priceLibraries() external view returns (address[] memory) { return state.priceLibraries; } } // File: contracts/core/extensions/CoreOperationState.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreOperationState * @author Set Protocol * * The CoreOperationState contract contains methods to alter state of variables that track * Core dependency addresses. */ contract CoreOperationState is Ownable, CoreState { /* ============ Enum ============ */ /** * Operational: * All Accounting and Issuance related functions are available for usage during this stage * * Shut Down: * Only functions which allow users to redeem and withdraw funds are allowed during this stage */ enum OperationState { Operational, ShutDown, InvalidState } /* ============ Events ============ */ event OperationStateChanged( uint8 _prevState, uint8 _newState ); /* ============ Modifiers ============ */ modifier whenOperational() { require( state.operationState == uint8(OperationState.Operational), "WhenOperational" ); _; } /* ============ External Functions ============ */ /** * Updates the operation state of the protocol. * Can only be called by owner of Core. * * @param _operationState Uint8 representing the current protocol operation state */ function setOperationState( uint8 _operationState ) external onlyOwner { require( _operationState < uint8(OperationState.InvalidState) && _operationState != state.operationState, "InvalidOperationState" ); emit OperationStateChanged( state.operationState, _operationState ); state.operationState = _operationState; } } // File: contracts/core/extensions/CoreAccounting.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreAccounting * @author Set Protocol * * The CoreAccounting contract interfaces with the vault and transfer proxies for * storage of tokenized assets. */ contract CoreAccounting is CoreState, CoreOperationState, ReentrancyGuard { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ External Functions ============ */ /** * Deposit a quantity of tokens to the vault and attribute to sender. * * @param _token Address of the token * @param _quantity Amount of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external nonReentrant whenOperational { // Don't deposit if quantity <= 0 if (_quantity > 0) { // Call TransferProxy contract to transfer user tokens to Vault state.transferProxyInstance.transfer( _token, _quantity, msg.sender, state.vault ); // Call Vault contract to attribute deposited tokens to user state.vaultInstance.incrementTokenOwner( _token, msg.sender, _quantity ); } } /** * Withdraw a quantity of tokens from the vault and deattribute from sender. * * @param _token Address of the token * @param _quantity Amount of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external nonReentrant { // Don't withdraw if quantity <= 0 if (_quantity > 0) { // Call Vault contract to deattribute withdrawn tokens from user state.vaultInstance.decrementTokenOwner( _token, msg.sender, _quantity ); // Call Vault contract to withdraw tokens from Vault to user state.vaultInstance.withdrawTo( _token, msg.sender, _quantity ); } } /** * Deposit multiple tokens to the vault and attribute to sender. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the tokens * @param _quantities Array of the amounts of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external nonReentrant whenOperational { // Call internal batch deposit function batchDepositInternal( msg.sender, msg.sender, _tokens, _quantities ); } /** * Withdraw multiple tokens from the vault and deattribute from sender. * Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the tokens * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external nonReentrant { // Call internal batch withdraw function batchWithdrawInternal( msg.sender, msg.sender, _tokens, _quantities ); } /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external nonReentrant whenOperational { state.vaultInstance.transferBalance( _token, msg.sender, _to, _quantity ); } /* ============ Internal Functions ============ */ /** * Internal function that deposits multiple tokens to the vault. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositInternal( address _from, address _to, address[] memory _tokens, uint256[] memory _quantities ) internal whenOperational { // Confirm an empty _tokens or quantity array is not passed CommonValidationsLibrary.validateNonEmpty(_tokens); // Confirm there is one quantity for every token address CommonValidationsLibrary.validateEqualLength(_tokens, _quantities); state.transferProxyInstance.batchTransfer( _tokens, _quantities, _from, state.vault ); state.vaultInstance.batchIncrementTokenOwner( _tokens, _to, _quantities ); } /** * Internal function that withdraws multiple tokens from the vault. * Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawInternal( address _from, address _to, address[] memory _tokens, uint256[] memory _quantities ) internal { // Confirm an empty _tokens or quantity array is not passed CommonValidationsLibrary.validateNonEmpty(_tokens); // Confirm there is one quantity for every token address CommonValidationsLibrary.validateEqualLength(_tokens, _quantities); // Call Vault contract to deattribute withdrawn tokens from user state.vaultInstance.batchDecrementTokenOwner( _tokens, _from, _quantities ); // Call Vault contract to withdraw tokens from Vault to user state.vaultInstance.batchWithdrawTo( _tokens, _to, _quantities ); } } // File: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /// @return Returns index and isIn for the first occurrence starting from /// end function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = length; i > 0; i--) { if (A[i - 1] == a) { return (i, true); } } return (0, false); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the combination of two storage arrays. * @param A The first array * @param B The second array * @return Returns A appended by a */ function sExtend(address[] storage A, address[] storage B) internal { uint256 length = B.length; for (uint256 i = 0; i < length; i++) { A.push(B[i]); } } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Alternate implementation * Assumes there are no duplicates */ function unionB(address[] memory A, address[] memory B) internal pure returns (address[] memory) { bool[] memory includeMap = new bool[](A.length + B.length); uint256 count = 0; for (uint256 i = 0; i < A.length; i++) { includeMap[i] = true; count++; } for (uint256 j = 0; j < B.length; j++) { if (!contains(A, B[j])) { includeMap[A.length + j] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 k = 0; for (uint256 m = 0; m < A.length; m++) { if (includeMap[m]) { newAddresses[k] = A[m]; k++; } } for (uint256 n = 0; n < B.length; n++) { if (includeMap[A.length + n]) { newAddresses[k] = B[n]; k++; } } return newAddresses; } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * @dev Reverses storage array in place */ function sReverse(address[] storage A) internal { address t; uint256 length = A.length; for (uint256 i = 0; i < length / 2; i++) { t = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = t; } } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } function sPop(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; for (uint256 i = index; i < length - 1; i++) { A[i] = A[i + 1]; } A.length--; return entry; } /** * Deletes address at index and fills the spot with the last address. * Order is not preserved. * @return Returns the removed entry */ function sPopCheap(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; if (index != length - 1) { A[index] = A[length - 1]; delete A[length - 1]; } A.length--; return entry; } /** * Deletes address at index. Works by swapping it with the last address, then deleting. * Order is not preserved * @param A Storage array to remove from */ function sRemoveCheap(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Error: entry not found"); } else { sPopCheap(A, index); return; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } /** * Returns the elements indexed at indexArray. * @param A The array to index * @param indexArray The array to use to index * @return Returns array containing elements indexed at indexArray */ function argGet(address[] memory A, uint256[] memory indexArray) internal pure returns (address[] memory) { address[] memory array = new address[](indexArray.length); for (uint256 i = 0; i < indexArray.length; i++) { array[i] = A[indexArray[i]]; } return array; } } // File: contracts/lib/TimeLockUpgrade.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title TimeLockUpgrade * @author Set Protocol * * The TimeLockUpgrade contract contains a modifier for handling minimum time period updates */ contract TimeLockUpgrade is Ownable { using SafeMath for uint256; /* ============ State Variables ============ */ // Timelock Upgrade Period in seconds uint256 public timeLockPeriod; // Mapping of upgradable units and initialized timelock mapping(bytes32 => uint256) public timeLockedUpgrades; /* ============ Events ============ */ event UpgradeRegistered( bytes32 _upgradeHash, uint256 _timestamp ); /* ============ Modifiers ============ */ modifier timeLockUpgrade() { // If the time lock period is 0, then allow non-timebound upgrades. // This is useful for initialization of the protocol and for testing. if (timeLockPeriod == 0) { _; return; } // The upgrade hash is defined by the hash of the transaction call data, // which uniquely identifies the function as well as the passed in arguments. bytes32 upgradeHash = keccak256( abi.encodePacked( msg.data ) ); uint256 registrationTime = timeLockedUpgrades[upgradeHash]; // If the upgrade hasn't been registered, register with the current time. if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; } require( block.timestamp >= registrationTime.add(timeLockPeriod), "TimeLockUpgrade: Time lock period must have elapsed." ); // Reset the timestamp to 0 timeLockedUpgrades[upgradeHash] = 0; // Run the rest of the upgrades _; } /* ============ Function ============ */ /** * Change timeLockPeriod period. Generally called after initially settings have been set up. * * @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution */ function setTimeLockPeriod( uint256 _timeLockPeriod ) external onlyOwner { // Only allow setting of the timeLockPeriod if the period is greater than the existing require( _timeLockPeriod > timeLockPeriod, "TimeLockUpgrade: New period must be greater than existing" ); timeLockPeriod = _timeLockPeriod; } } // File: contracts/core/extensions/CoreAdmin.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreAdmin * @author Set Protocol * * The CoreAdmin contract contains methods to alter state of variables that track * Core dependency addresses. */ contract CoreAdmin is Ownable, CoreState, TimeLockUpgrade { using AddressArrayUtils for address[]; /* ============ Events ============ */ event FactoryAdded( address _factory ); event FactoryRemoved( address _factory ); event ExchangeAdded( uint8 _exchangeId, address _exchange ); event ExchangeRemoved( uint8 _exchangeId ); event ModuleAdded( address _module ); event ModuleRemoved( address _module ); event SetDisabled( address _set ); event SetReenabled( address _set ); event PriceLibraryAdded( address _priceLibrary ); event PriceLibraryRemoved( address _priceLibrary ); /* ============ External Functions ============ */ /** * Add a factory from the mapping of tracked factories. * Can only be called by owner of Core. * * @param _factory Address of the factory conforming to ISetFactory */ function addFactory( address _factory ) external onlyOwner timeLockUpgrade { require( !state.validFactories[_factory] ); state.validFactories[_factory] = true; state.factories = state.factories.append(_factory); emit FactoryAdded( _factory ); } /** * Remove a factory from the mapping of tracked factories. * Can only be called by owner of Core. * * @param _factory Address of the factory conforming to ISetFactory */ function removeFactory( address _factory ) external onlyOwner { require( state.validFactories[_factory] ); state.factories = state.factories.remove(_factory); state.validFactories[_factory] = false; emit FactoryRemoved( _factory ); } /** * Add an exchange address with the mapping of tracked exchanges. * Can only be called by owner of Core. * * @param _exchangeId Enumeration of exchange within the mapping * @param _exchange Address of the exchange conforming to IExchangeWrapper */ function addExchange( uint8 _exchangeId, address _exchange ) external onlyOwner timeLockUpgrade { require( state.exchangeIds[_exchangeId] == address(0) ); state.exchangeIds[_exchangeId] = _exchange; state.exchanges = state.exchanges.append(_exchange); emit ExchangeAdded( _exchangeId, _exchange ); } /** * Remove an exchange address with the mapping of tracked exchanges. * Can only be called by owner of Core. * * @param _exchangeId Enumeration of exchange within the mapping * @param _exchange Address of the exchange conforming to IExchangeWrapper */ function removeExchange( uint8 _exchangeId, address _exchange ) external onlyOwner { require( state.exchangeIds[_exchangeId] != address(0) && state.exchangeIds[_exchangeId] == _exchange ); state.exchanges = state.exchanges.remove(_exchange); state.exchangeIds[_exchangeId] = address(0); emit ExchangeRemoved( _exchangeId ); } /** * Add a module address with the mapping of tracked modules. * Can only be called by owner of Core. * * @param _module Address of the module */ function addModule( address _module ) external onlyOwner timeLockUpgrade { require( !state.validModules[_module] ); state.validModules[_module] = true; state.modules = state.modules.append(_module); emit ModuleAdded( _module ); } /** * Remove a module address with the mapping of tracked modules. * Can only be called by owner of Core. * * @param _module Enumeration of module within the mapping */ function removeModule( address _module ) external onlyOwner { require( state.validModules[_module] ); state.modules = state.modules.remove(_module); state.validModules[_module] = false; emit ModuleRemoved( _module ); } /** * Disables a Set from the mapping and array of tracked Sets. * Can only be called by owner of Core. * * @param _set Address of the Set */ function disableSet( address _set ) external onlyOwner { require( state.validSets[_set] ); state.setTokens = state.setTokens.remove(_set); state.validSets[_set] = false; state.disabledSets[_set] = true; emit SetDisabled( _set ); } /** * Enables a Set from the mapping and array of tracked Sets if it has been previously disabled * Can only be called by owner of Core. * * @param _set Address of the Set */ function reenableSet( address _set ) external onlyOwner { require( state.disabledSets[_set] ); state.setTokens = state.setTokens.append(_set); state.validSets[_set] = true; state.disabledSets[_set] = false; emit SetReenabled( _set ); } /** * Add a price library from the mapping of tracked price libraries. * Can only be called by owner of Core. * * @param _priceLibrary Address of the price library */ function addPriceLibrary( address _priceLibrary ) external onlyOwner timeLockUpgrade { require( !state.validPriceLibraries[_priceLibrary] ); state.validPriceLibraries[_priceLibrary] = true; state.priceLibraries = state.priceLibraries.append(_priceLibrary); emit PriceLibraryAdded( _priceLibrary ); } /** * Remove a price library from the mapping of tracked price libraries. * Can only be called by owner of Core. * * @param _priceLibrary Address of the price library */ function removePriceLibrary( address _priceLibrary ) external onlyOwner { require( state.validPriceLibraries[_priceLibrary] ); state.priceLibraries = state.priceLibraries.remove(_priceLibrary); state.validPriceLibraries[_priceLibrary] = false; emit PriceLibraryRemoved( _priceLibrary ); } } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/extensions/CoreFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreFactory * @author Set Protocol * * The CoreFactory contract contains Set Token creation operations */ contract CoreFactory is CoreState { /* ============ Events ============ */ event SetTokenCreated( address indexed _setTokenAddress, address _factory, address[] _components, uint256[] _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol ); /* ============ External Functions ============ */ /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address) { // Verify Factory is linked to Core require( state.validFactories[_factory], "CreateSet" ); // Create the Set address newSetTokenAddress = ISetFactory(_factory).createSet( _components, _units, _naturalUnit, _name, _symbol, _callData ); // Add Set to the mapping of tracked Sets state.validSets[newSetTokenAddress] = true; // Add Set to the array of tracked Sets state.setTokens.push(newSetTokenAddress); // Emit Set Token creation log emit SetTokenCreated( newSetTokenAddress, _factory, _components, _units, _naturalUnit, _name, _symbol ); return newSetTokenAddress; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/core/lib/CoreIssuanceLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreIssuanceLibrary * @author Set Protocol * * This library contains functions for calculating deposit, withdrawal,and transfer quantities */ library CoreIssuanceLibrary { using SafeMath for uint256; /** * Calculate the quantities required to deposit and decrement during issuance. Takes into account * the tokens an owner already has in the vault. * * @param _components Addresses of components * @param _componentQuantities Component quantities to increment and withdraw * @param _owner Address to deposit and decrement quantities from * @param _vault Address to vault * @return uint256[] decrementQuantities Quantities to decrement from vault * @return uint256[] depositQuantities Quantities to deposit into the vault */ function calculateDepositAndDecrementQuantities( address[] calldata _components, uint256[] calldata _componentQuantities, address _owner, address _vault ) external view returns ( uint256[] memory /* decrementQuantities */, uint256[] memory /* depositQuantities */ ) { uint256 componentCount = _components.length; uint256[] memory decrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory depositQuantities = new uint256[](componentCount); for (uint256 i = 0; i < componentCount; i++) { // Fetch component quantity in vault uint256 vaultBalance = IVault(_vault).getOwnerBalance( _components[i], _owner ); // If the vault holds enough components, decrement the full amount if (vaultBalance >= _componentQuantities[i]) { decrementTokenOwnerValues[i] = _componentQuantities[i]; } else { // User has less than required amount, decrement the vault by full balance if (vaultBalance > 0) { decrementTokenOwnerValues[i] = vaultBalance; } depositQuantities[i] = _componentQuantities[i].sub(vaultBalance); } } return ( decrementTokenOwnerValues, depositQuantities ); } /** * Calculate the quantities required to withdraw and increment during redeem and withdraw. Takes into * account a bitmask exclusion parameter. * * @param _componentQuantities Component quantities to increment and withdraw * @param _toExclude Mask of indexes of tokens to exclude from withdrawing * @return uint256[] incrementQuantities Quantities to increment in vault * @return uint256[] withdrawQuantities Quantities to withdraw from vault */ function calculateWithdrawAndIncrementQuantities( uint256[] calldata _componentQuantities, uint256 _toExclude ) external pure returns ( uint256[] memory /* incrementQuantities */, uint256[] memory /* withdrawQuantities */ ) { uint256 componentCount = _componentQuantities.length; uint256[] memory incrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory withdrawToValues = new uint256[](componentCount); // Loop through and decrement vault balances for the set, withdrawing if requested for (uint256 i = 0; i < componentCount; i++) { // Calculate bit index of current component uint256 componentBitIndex = CommonMath.safePower(2, i); // Transfer to user unless component index is included in _toExclude if ((_toExclude & componentBitIndex) != 0) { incrementTokenOwnerValues[i] = _componentQuantities[i]; } else { withdrawToValues[i] = _componentQuantities[i]; } } return ( incrementTokenOwnerValues, withdrawToValues ); } /** * Calculate the required component quantities required for issuance or rdemption for a given * quantity of Set Tokens * * @param _componentUnits The units of the component token * @param _naturalUnit The natural unit of the Set token * @param _quantity The number of tokens being redeem * @return uint256[] Required quantities in base units of components */ function calculateRequiredComponentQuantities( uint256[] calldata _componentUnits, uint256 _naturalUnit, uint256 _quantity ) external pure returns (uint256[] memory) { require( _quantity.mod(_naturalUnit) == 0, "CoreIssuanceLibrary: Quantity must be a multiple of nat unit" ); uint256[] memory tokenValues = new uint256[](_componentUnits.length); // Transfer the underlying tokens to the corresponding token balances for (uint256 i = 0; i < _componentUnits.length; i++) { tokenValues[i] = _quantity.div(_naturalUnit).mul(_componentUnits[i]); } return tokenValues; } } // File: contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * 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 ) external; } // File: contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/core/extensions/CoreIssuance.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreIssuance * @author Set Protocol * * The CoreIssuance contract contains function related to issuing and redeeming Sets. */ contract CoreIssuance is CoreState, CoreOperationState, ReentrancyGuard { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ Events ============ */ event SetIssued( address _setAddress, uint256 _quantity ); event SetRedeemed( address _setAddress, uint256 _quantity ); /* ============ External Functions ============ */ /** * Issues a specified Set for a specified quantity to the caller * using the caller's components from the wallet and vault. * * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issue( address _set, uint256 _quantity ) external nonReentrant { issueInternal( msg.sender, msg.sender, _set, _quantity ); } /** * Converts user's components into Set Tokens owned by the user and stored in Vault * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external nonReentrant { issueInVaultInternal( msg.sender, _set, _quantity ); } /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external nonReentrant { issueInternal( msg.sender, _recipient, _set, _quantity ); } /** * Exchange Set tokens for underlying components to the user held in the Vault. * * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeem( address _set, uint256 _quantity ) external nonReentrant { redeemInternal( msg.sender, msg.sender, _set, _quantity ); } /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external nonReentrant { uint256[] memory componentTransferValues = redeemAndDecrementVault( _set, msg.sender, _quantity ); // Calculate the withdraw and increment quantities to specified address uint256[] memory incrementTokenOwnerValues; uint256[] memory withdrawToValues; ( incrementTokenOwnerValues, withdrawToValues ) = CoreIssuanceLibrary.calculateWithdrawAndIncrementQuantities( componentTransferValues, _toExclude ); address[] memory components = ISetToken(_set).getComponents(); // Increment excluded components to the specified address state.vaultInstance.batchIncrementTokenOwner( components, _to, incrementTokenOwnerValues ); // Withdraw non-excluded components and attribute to specified address state.vaultInstance.batchWithdrawTo( components, _to, withdrawToValues ); } /** * Convert the caller's Set tokens held in the vault into underlying components to the user * held in the Vault. * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemInVault( address _set, uint256 _quantity ) external nonReentrant { // Decrement ownership of Set token in the vault state.vaultInstance.decrementTokenOwner( _set, msg.sender, _quantity ); redeemInternal( state.vault, msg.sender, _set, _quantity ); } /** * Redeem Set token and return components to specified recipient. The components * are left in the vault after redemption in the recipient's name. * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external nonReentrant { redeemInternal( msg.sender, _recipient, _set, _quantity ); } /* ============ Internal Functions ============ */ /** * Exchange components for Set tokens, accepting any owner * Used in issue, issueTo, and issueInVaultInternal * * @param _componentOwner Address to use tokens from * @param _setRecipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueInternal( address _componentOwner, address _setRecipient, address _set, uint256 _quantity ) internal whenOperational { // Verify Set was created by Core and is enabled require( state.validSets[_set], "IssueInternal" ); // Validate quantity is multiple of natural unit SetTokenLibrary.isMultipleOfSetNaturalUnit(_set, _quantity); SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(_set); // Calculate component quantities required to issue uint256[] memory requiredComponentQuantities = CoreIssuanceLibrary.calculateRequiredComponentQuantities( setToken.units, setToken.naturalUnit, _quantity ); // Calculate the withdraw and increment quantities to caller uint256[] memory decrementTokenOwnerValues; uint256[] memory depositValues; ( decrementTokenOwnerValues, depositValues ) = CoreIssuanceLibrary.calculateDepositAndDecrementQuantities( setToken.components, requiredComponentQuantities, _componentOwner, state.vault ); // Decrement components used for issuance in vault state.vaultInstance.batchDecrementTokenOwner( setToken.components, _componentOwner, decrementTokenOwnerValues ); // Deposit tokens used for issuance into vault state.transferProxyInstance.batchTransfer( setToken.components, depositValues, _componentOwner, state.vault ); // Increment the vault balance of the set token for the components state.vaultInstance.batchIncrementTokenOwner( setToken.components, _set, requiredComponentQuantities ); // Issue set token ISetToken(_set).mint( _setRecipient, _quantity ); emit SetIssued( _set, _quantity ); } /** * Converts recipient's components into Set Tokens held directly in Vault. * Used in issueInVault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to issue */ function issueInVaultInternal( address _recipient, address _set, uint256 _quantity ) internal { issueInternal( _recipient, state.vault, _set, _quantity ); // Increment ownership of Set token in the vault state.vaultInstance.incrementTokenOwner( _set, _recipient, _quantity ); } /** * Exchange Set tokens for underlying components. Components are attributed in the vault. * Used in redeem, redeemInVault, and redeemTo * * @param _burnAddress Address to burn tokens from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemInternal( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) internal { uint256[] memory componentQuantities = redeemAndDecrementVault( _set, _burnAddress, _quantity ); // Increment the component amount address[] memory components = ISetToken(_set).getComponents(); state.vaultInstance.batchIncrementTokenOwner( components, _incrementAddress, componentQuantities ); } /** * Private method that validates inputs, redeems Set, and decrements * the components in the vault * * @param _set Address of the Set to redeem * @param _burnAddress Address to burn tokens from * @param _quantity Number of tokens to redeem * @return componentQuantities Transfer value of components */ function redeemAndDecrementVault( address _set, address _burnAddress, uint256 _quantity ) private returns (uint256[] memory) { // Verify Set was created by Core and is enabled require( state.validSets[_set], "RedeemAndDecrementVault" ); // Validate quantity is multiple of natural unit SetTokenLibrary.isMultipleOfSetNaturalUnit(_set, _quantity); // Burn the Set token (thereby decrementing the Set balance) ISetToken(_set).burn( _burnAddress, _quantity ); SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(_set); // Calculate component quantities to redeem uint256[] memory componentQuantities = CoreIssuanceLibrary.calculateRequiredComponentQuantities( setToken.units, setToken.naturalUnit, _quantity ); // Decrement components from Set's possession state.vaultInstance.batchDecrementTokenOwner( setToken.components, _set, componentQuantities ); emit SetRedeemed( _set, _quantity ); return componentQuantities; } } // File: contracts/core/interfaces/ICoreAccounting.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICoreAccounting * @author Set Protocol * * The ICoreAccounting Contract defines all the functions exposed in the CoreIssuance * extension. */ contract ICoreAccounting { /* ============ Internal Functions ============ */ /** * Internal function that deposits multiple tokens to the vault. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositInternal( address _from, address _to, address[] memory _tokens, uint[] memory _quantities ) internal; /** * Internal function that withdraws multiple tokens from the vault. * Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawInternal( address _from, address _to, address[] memory _tokens, uint256[] memory _quantities ) internal; } // File: contracts/core/interfaces/ICoreIssuance.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICoreIssuance * @author Set Protocol * * The ICoreIssuance Contract defines all the functions exposed in the CoreIssuance * extension. */ contract ICoreIssuance { /* ============ Internal Functions ============ */ /** * Exchange components for Set tokens, accepting any owner * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueInternal( address _owner, address _recipient, address _set, uint256 _quantity ) internal; /** * Converts recipient's components into Set Tokens held directly in Vault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to issue */ function issueInVaultInternal( address _recipient, address _set, uint256 _quantity ) internal; /** * Exchange Set tokens for underlying components * * @param _burnAddress Address to burn tokens from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemInternal( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) internal; } // File: contracts/core/extensions/CoreModuleInteraction.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreModularInteraction * @author Set Protocol * * Extension used to expose internal accounting and issuance functions, vault, and proxy functions * to modules. */ contract CoreModuleInteraction is ICoreAccounting, ICoreIssuance, CoreState, ReentrancyGuard { modifier onlyModule() { onlyModuleCallable(); _; } function onlyModuleCallable() internal view { require( state.validModules[msg.sender], "OnlyModule" ); } /** * Exposes internal function that deposits tokens to the vault, exposed to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _token Address of the token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external onlyModule { address[] memory tokenArray = new address[](1); tokenArray[0] = _token; uint256[] memory quantityArray = new uint256[](1); quantityArray[0] = _quantity; batchDepositInternal( _from, _to, tokenArray, quantityArray ); } /** * Exposes internal function that deposits multiple tokens to the vault, exposed to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external onlyModule { batchDepositInternal( _from, _to, _tokens, _quantities ); } /** * Exposes internal function that withdraws multiple tokens to the vault, exposed to system * modules. Quantities should be in the order of the addresses of the tokens being * withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _token Address of the token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external onlyModule { address[] memory tokenArray = new address[](1); tokenArray[0] = _token; uint256[] memory quantityArray = new uint256[](1); quantityArray[0] = _quantity; batchWithdrawInternal( _from, _to, tokenArray, quantityArray ); } /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external onlyModule { batchWithdrawInternal( _from, _to, _tokens, _quantities ); } /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _componentOwner Address to use tokens from * @param _setRecipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _componentOwner, address _setRecipient, address _set, uint256 _quantity ) external onlyModule { issueInternal( _componentOwner, _setRecipient, _set, _quantity ); } /** * Converts recipient's components into Set Token's held directly in Vault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVaultModule( address _recipient, address _set, uint256 _quantity ) external onlyModule { issueInVaultInternal( _recipient, _set, _quantity ); } /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external onlyModule { redeemInternal( _burnAddress, _incrementAddress, _set, _quantity ); } /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external onlyModule { state.vaultInstance.batchIncrementTokenOwner( _tokens, _owner, _quantities ); } /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external onlyModule { state.vaultInstance.batchDecrementTokenOwner( _tokens, _owner, _quantities ); } /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external onlyModule { state.vaultInstance.batchTransferBalance( _tokens, _from, _to, _quantities ); } /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external onlyModule { state.transferProxyInstance.transfer( _token, _quantity, _from, _to ); } /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external onlyModule { state.transferProxyInstance.batchTransfer( _tokens, _quantities, _from, _to ); } } // File: contracts/core/Core.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Core * @author Set Protocol * * The Core contract acts as a coordinator handling issuing, redeeming, and * creating Sets, as well as all collateral flows throughout the system. Core * is also responsible for tracking state and exposing methods to modules */ /* solium-disable-next-line no-empty-blocks */ contract Core is CoreAccounting, CoreAdmin, CoreFactory, CoreIssuance, CoreModuleInteraction { /** * Constructor function for Core * * @param _transferProxy The address of the transfer proxy * @param _vault The address of the vault */ constructor( address _transferProxy, address _vault ) public { // Commit passed address to transferProxyAddress state variable state.transferProxy = _transferProxy; // Instantiate instance of transferProxy state.transferProxyInstance = ITransferProxy(_transferProxy); // Commit passed address to vault state variable state.vault = _vault; // Instantiate instance of vault state.vaultInstance = IVault(_vault); } }
File 3 of 10: Vault
// File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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; } } // File: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /// @return Returns index and isIn for the first occurrence starting from /// end function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = length; i > 0; i--) { if (A[i - 1] == a) { return (i, true); } } return (0, false); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the combination of two storage arrays. * @param A The first array * @param B The second array * @return Returns A appended by a */ function sExtend(address[] storage A, address[] storage B) internal { uint256 length = B.length; for (uint256 i = 0; i < length; i++) { A.push(B[i]); } } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Alternate implementation * Assumes there are no duplicates */ function unionB(address[] memory A, address[] memory B) internal pure returns (address[] memory) { bool[] memory includeMap = new bool[](A.length + B.length); uint256 count = 0; for (uint256 i = 0; i < A.length; i++) { includeMap[i] = true; count++; } for (uint256 j = 0; j < B.length; j++) { if (!contains(A, B[j])) { includeMap[A.length + j] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 k = 0; for (uint256 m = 0; m < A.length; m++) { if (includeMap[m]) { newAddresses[k] = A[m]; k++; } } for (uint256 n = 0; n < B.length; n++) { if (includeMap[A.length + n]) { newAddresses[k] = B[n]; k++; } } return newAddresses; } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * @dev Reverses storage array in place */ function sReverse(address[] storage A) internal { address t; uint256 length = A.length; for (uint256 i = 0; i < length / 2; i++) { t = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = t; } } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } function sPop(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; for (uint256 i = index; i < length - 1; i++) { A[i] = A[i + 1]; } A.length--; return entry; } /** * Deletes address at index and fills the spot with the last address. * Order is not preserved. * @return Returns the removed entry */ function sPopCheap(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; if (index != length - 1) { A[index] = A[length - 1]; delete A[length - 1]; } A.length--; return entry; } /** * Deletes address at index. Works by swapping it with the last address, then deleting. * Order is not preserved * @param A Storage array to remove from */ function sRemoveCheap(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Error: entry not found"); } else { sPopCheap(A, index); return; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } /** * Returns the elements indexed at indexArray. * @param A The array to index * @param indexArray The array to use to index * @return Returns array containing elements indexed at indexArray */ function argGet(address[] memory A, uint256[] memory indexArray) internal pure returns (address[] memory) { address[] memory array = new address[](indexArray.length); for (uint256 i = 0; i < indexArray.length; i++) { array[i] = A[indexArray[i]]; } return array; } } // File: contracts/lib/TimeLockUpgrade.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title TimeLockUpgrade * @author Set Protocol * * The TimeLockUpgrade contract contains a modifier for handling minimum time period updates */ contract TimeLockUpgrade is Ownable { using SafeMath for uint256; /* ============ State Variables ============ */ // Timelock Upgrade Period in seconds uint256 public timeLockPeriod; // Mapping of upgradable units and initialized timelock mapping(bytes32 => uint256) public timeLockedUpgrades; /* ============ Events ============ */ event UpgradeRegistered( bytes32 _upgradeHash, uint256 _timestamp ); /* ============ Modifiers ============ */ modifier timeLockUpgrade() { // If the time lock period is 0, then allow non-timebound upgrades. // This is useful for initialization of the protocol and for testing. if (timeLockPeriod == 0) { _; return; } // The upgrade hash is defined by the hash of the transaction call data, // which uniquely identifies the function as well as the passed in arguments. bytes32 upgradeHash = keccak256( abi.encodePacked( msg.data ) ); uint256 registrationTime = timeLockedUpgrades[upgradeHash]; // If the upgrade hasn't been registered, register with the current time. if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; } require( block.timestamp >= registrationTime.add(timeLockPeriod), "TimeLockUpgrade: Time lock period must have elapsed." ); // Reset the timestamp to 0 timeLockedUpgrades[upgradeHash] = 0; // Run the rest of the upgrades _; } /* ============ Function ============ */ /** * Change timeLockPeriod period. Generally called after initially settings have been set up. * * @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution */ function setTimeLockPeriod( uint256 _timeLockPeriod ) external onlyOwner { // Only allow setting of the timeLockPeriod if the period is greater than the existing require( _timeLockPeriod > timeLockPeriod, "TimeLockUpgrade: New period must be greater than existing" ); timeLockPeriod = _timeLockPeriod; } } // File: contracts/lib/Authorizable.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Authorizable * @author Set Protocol * * The Authorizable contract is an inherited contract that sets permissions on certain function calls * through the onlyAuthorized modifier. Permissions can be managed only by the Owner of the contract. */ contract Authorizable is Ownable, TimeLockUpgrade { using SafeMath for uint256; using AddressArrayUtils for address[]; /* ============ State Variables ============ */ // Mapping of addresses to bool indicator of authorization mapping (address => bool) public authorized; // Array of authorized addresses address[] public authorities; /* ============ Modifiers ============ */ // Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require( authorized[msg.sender], "Authorizable.onlyAuthorized: Sender not included in authorities" ); _; } /* ============ Events ============ */ // Event emitted when new address is authorized. event AddressAuthorized ( address indexed authAddress, address authorizedBy ); // Event emitted when address is deauthorized. event AuthorizedAddressRemoved ( address indexed addressRemoved, address authorizedBy ); /* ============ Setters ============ */ /** * Add authorized address to contract. Can only be set by owner. * * @param _authTarget The address of the new authorized contract */ function addAuthorizedAddress(address _authTarget) external onlyOwner timeLockUpgrade { // Require that address is not already authorized require( !authorized[_authTarget], "Authorizable.addAuthorizedAddress: Address already registered" ); // Set address authority to true authorized[_authTarget] = true; // Add address to authorities array authorities.push(_authTarget); // Emit authorized address event emit AddressAuthorized( _authTarget, msg.sender ); } /** * Remove authorized address from contract. Can only be set by owner. * * @param _authTarget The address to be de-permissioned */ function removeAuthorizedAddress(address _authTarget) external onlyOwner { // Require address is authorized require( authorized[_authTarget], "Authorizable.removeAuthorizedAddress: Address not authorized" ); // Delete address from authorized mapping authorized[_authTarget] = false; authorities = authorities.remove(_authTarget); // Emit AuthorizedAddressRemoved event. emit AuthorizedAddressRemoved( _authTarget, msg.sender ); } /* ============ Getters ============ */ /** * Get array of authorized addresses. * * @return address[] Array of authorized addresses */ function getAuthorizedAddresses() external view returns (address[] memory) { // Return array of authorized addresses return authorities; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/lib/IERC20.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IERC20 * @author Set Protocol * * Interface for using ERC20 Tokens. This interface is needed to interact with tokens that are not * fully ERC20 compliant and return something other than true on successful transfers. */ interface IERC20 { function balanceOf( address _owner ) external view returns (uint256); function allowance( address _owner, address _spender ) external view returns (uint256); function transfer( address _to, uint256 _quantity ) external; function transferFrom( address _from, address _to, uint256 _quantity ) external; function approve( address _spender, uint256 _quantity ) external returns (bool); } // File: contracts/lib/ERC20Wrapper.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ERC20Wrapper * @author Set Protocol * * This library contains functions for interacting wtih ERC20 tokens, even those not fully compliant. * For all functions we will only accept tokens that return a null or true value, any other values will * cause the operation to revert. */ library ERC20Wrapper { // ============ Internal Functions ============ /** * Check balance owner's balance of ERC20 token * * @param _token The address of the ERC20 token * @param _owner The owner who's balance is being checked * @return uint256 The _owner's amount of tokens */ function balanceOf( address _token, address _owner ) external view returns (uint256) { return IERC20(_token).balanceOf(_owner); } /** * Checks spender's allowance to use token's on owner's behalf. * * @param _token The address of the ERC20 token * @param _owner The token owner address * @param _spender The address the allowance is being checked on * @return uint256 The spender's allowance on behalf of owner */ function allowance( address _token, address _owner, address _spender ) internal view returns (uint256) { return IERC20(_token).allowance(_owner, _spender); } /** * Transfers tokens from an address. Handle's tokens that return true or null. * If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _to The address to transfer to * @param _quantity The amount of tokens to transfer */ function transfer( address _token, address _to, uint256 _quantity ) external { IERC20(_token).transfer(_to, _quantity); // Check that transfer returns true or null require( checkSuccess(), "ERC20Wrapper.transfer: Bad return value" ); } /** * Transfers tokens from an address (that has set allowance on the proxy). * Handle's tokens that return true or null. If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom( address _token, address _from, address _to, uint256 _quantity ) external { IERC20(_token).transferFrom(_from, _to, _quantity); // Check that transferFrom returns true or null require( checkSuccess(), "ERC20Wrapper.transferFrom: Bad return value" ); } /** * Grants spender ability to spend on owner's behalf. * Handle's tokens that return true or null. If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _spender The address to approve for transfer * @param _quantity The amount of tokens to approve spender for */ function approve( address _token, address _spender, uint256 _quantity ) internal { IERC20(_token).approve(_spender, _quantity); // Check that approve returns true or null require( checkSuccess(), "ERC20Wrapper.approve: Bad return value" ); } /** * Ensure's the owner has granted enough allowance for system to * transfer tokens. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _spender The address to grant/check allowance for * @param _quantity The amount to see if allowed for */ function ensureAllowance( address _token, address _owner, address _spender, uint256 _quantity ) internal { uint256 currentAllowance = allowance(_token, _owner, _spender); if (currentAllowance < _quantity) { approve( _token, _spender, CommonMath.maxUInt256() ); } } // ============ Private Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 1. */ function checkSuccess( ) private pure returns (bool) { // default to failure uint256 returnValue = 0; assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } // check if returned value is one or nothing return returnValue == 1; } } // File: contracts/core/Vault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Vault * @author Set Protocol * * The vault contract is responsible for holding all funds and keeping track of the * fund state and which Sets own which funds. * */ contract Vault is Authorizable { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ State Variables ============ */ // Mapping of token address to map of owner or Set address to balance. // Example of mapping below: // +--------------+---------------------+--------+ // | TokenAddress | Set OR User Address | Amount | // +--------------+---------------------+--------+ // | TokenA | User 0x123 | 500 | // | | User 0xABC | 300 | // | | Set 0x456 | 1000 | // | TokenB | User 0xDEF | 100 | // | | Set 0xSET | 700 | // +--------------+---------------------+--------+ mapping (address => mapping (address => uint256)) public balances; /* ============ External Functions ============ */ /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) public onlyAuthorized { if (_quantity > 0) { // Retrieve current balance of token for the vault uint256 existingVaultBalance = ERC20Wrapper.balanceOf( _token, address(this) ); // Call specified ERC20 token contract to transfer tokens from Vault to user ERC20Wrapper.transfer( _token, _to, _quantity ); // Verify transfer quantity is reflected in balance uint256 newVaultBalance = ERC20Wrapper.balanceOf( _token, address(this) ); // Check to make sure current balances are as expected require( newVaultBalance == existingVaultBalance.sub(_quantity), "Vault.withdrawTo: Invalid post withdraw balance" ); } } /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) public onlyAuthorized { if (_quantity > 0) { // Increment balances state variable adding _quantity to user's token amount balances[_token][_owner] = balances[_token][_owner].add(_quantity); } } /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) public onlyAuthorized { // Require that user has enough unassociated tokens to withdraw tokens or issue Set require( balances[_token][_owner] >= _quantity, "Vault.decrementTokenOwner: Insufficient token balance" ); if (_quantity > 0) { // Decrement balances state variable subtracting _quantity to user's token amount balances[_token][_owner] = balances[_token][_owner].sub(_quantity); } } /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) public onlyAuthorized { if (_quantity > 0) { // Require that user has enough unassociated tokens to withdraw tokens or issue Set require( balances[_token][_from] >= _quantity, "Vault.transferBalance: Insufficient token balance" ); // Decrement balances state variable subtracting _quantity to user's token amount balances[_token][_from] = balances[_token][_from].sub(_quantity); // Increment balances state variable adding _quantity to user's token amount balances[_token][_to] = balances[_token][_to].add(_quantity); } } /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _to The address of the recipient * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external onlyAuthorized { // Storing token count to local variable to save on invocation uint256 tokenCount = _tokens.length; // Confirm and empty _tokens array is not passed require( tokenCount > 0, "Vault.batchWithdrawTo: Tokens must not be empty" ); // Confirm there is one quantity for every token address require( tokenCount == _quantities.length, "Vault.batchWithdrawTo: Tokens and quantities lengths mismatch" ); for (uint256 i = 0; i < tokenCount; i++) { withdrawTo( _tokens[i], _to, _quantities[i] ); } } /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external onlyAuthorized { // Storing token count to local variable to save on invocation uint256 tokenCount = _tokens.length; // Confirm and empty _tokens array is not passed require( tokenCount > 0, "Vault.batchIncrementTokenOwner: Tokens must not be empty" ); // Confirm there is one quantity for every token address require( tokenCount == _quantities.length, "Vault.batchIncrementTokenOwner: Tokens and quantities lengths mismatch" ); for (uint256 i = 0; i < tokenCount; i++) { incrementTokenOwner( _tokens[i], _owner, _quantities[i] ); } } /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external onlyAuthorized { // Storing token count to local variable to save on invocation uint256 tokenCount = _tokens.length; // Confirm and empty _tokens array is not passed require( tokenCount > 0, "Vault.batchDecrementTokenOwner: Tokens must not be empty" ); // Confirm there is one quantity for every token address require( tokenCount == _quantities.length, "Vault.batchDecrementTokenOwner: Tokens and quantities lengths mismatch" ); for (uint256 i = 0; i < tokenCount; i++) { decrementTokenOwner( _tokens[i], _owner, _quantities[i] ); } } /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external onlyAuthorized { // Storing token count to local variable to save on invocation uint256 tokenCount = _tokens.length; // Confirm and empty _tokens array is not passed require( tokenCount > 0, "Vault.batchTransferBalance: Tokens must not be empty" ); // Confirm there is one quantity for every token address require( tokenCount == _quantities.length, "Vault.batchTransferBalance: Tokens and quantities lengths mismatch" ); for (uint256 i = 0; i < tokenCount; i++) { transferBalance( _tokens[i], _from, _to, _quantities[i] ); } } /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256) { // Return owners token balance return balances[_token][_owner]; } }
File 4 of 10: SetToken
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @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. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; 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 _allowed[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, _allowed[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 _allowed[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, _allowed[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 _allowed[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, _allowed[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)); _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)); _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)); _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(spender != address(0)); require(owner != address(0)); _allowed[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, _allowed[account][msg.sender].sub(value)); } } // File: contracts/lib/CommonValidationsLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonValidationsLibrary { /** * Ensures that an address array is not empty. * * @param _addressArray Address array input */ function validateNonEmpty( address[] calldata _addressArray ) external pure { require( _addressArray.length > 0, "Address array length must be > 0" ); } /** * Ensures that an address array and uint256 array are equal length * * @param _addressArray Address array input * @param _uint256Array Uint256 array input */ function validateEqualLength( address[] calldata _addressArray, uint256[] calldata _uint256Array ) external pure { require( _addressArray.length == _uint256Array.length, "Input length mismatch" ); } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/tokens/SetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title SetToken * @author Set Protocol * * Implementation of the basic Set token. */ contract SetToken is ERC20, ERC20Detailed { using SafeMath for uint256; /* ============ State Variables ============ */ uint256 public naturalUnit; address[] public components; uint256[] public units; // Mapping of componentHash to isComponent mapping(address => bool) internal isComponent; // Address of the Factory contract that created the SetToken address public factory; /* ============ Constructor ============ */ /** * Constructor function for Set token * * As looping operations are expensive, checking for duplicates will be on the onus of the application developer * * @param _factory The factory used to create the Set Token * @param _components A list of component address which you want to include * @param _units A list of quantities of each component (corresponds to the Set of _components) * @param _naturalUnit The minimum multiple of Sets that can be issued or redeemed * @param _name The Set's name * @param _symbol The Set's symbol */ constructor( address _factory, address[] memory _components, uint256[] memory _units, uint256 _naturalUnit, string memory _name, string memory _symbol ) public ERC20Detailed( _name, _symbol, 18 ) { // Storing count and unit counts to local variable to save on invocation uint256 unitCount = _units.length; // Require naturalUnit passed is greater than 0 require( _naturalUnit > 0, "SetToken.constructor: Natural unit must be positive" ); // Confirm an empty _components array is not passed CommonValidationsLibrary.validateNonEmpty(_components); // Confirm there is one quantity for every token address CommonValidationsLibrary.validateEqualLength(_components, _units); // NOTE: It will be the onus of developers to check whether the addressExists // are in fact ERC20 addresses uint8 minDecimals = 18; uint8 currentDecimals; for (uint256 i = 0; i < unitCount; i++) { // Check that all units are non-zero uint256 currentUnits = _units[i]; require( currentUnits > 0, "SetToken.constructor: Units must be positive" ); // Check that all addresses are non-zero address currentComponent = _components[i]; require( currentComponent != address(0), "SetToken.constructor: Invalid component address" ); // Figure out which of the components has the minimum decimal value /* solium-disable-next-line security/no-low-level-calls */ (bool success, ) = currentComponent.call(abi.encodeWithSignature("decimals()")); if (success) { currentDecimals = ERC20Detailed(currentComponent).decimals(); minDecimals = currentDecimals < minDecimals ? currentDecimals : minDecimals; } else { // If one of the components does not implement decimals, we assume the worst // and set minDecimals to 0 minDecimals = 0; } // Check the component has not already been added require( !tokenIsComponent(currentComponent), "SetToken.constructor: Duplicated component" ); // Add component to isComponent mapping isComponent[currentComponent] = true; // Add component data to components and units state variables components.push(currentComponent); units.push(currentUnits); } // This is the minimum natural unit possible for a Set with these components. require( _naturalUnit >= CommonMath.safePower(10, uint256(18).sub(minDecimals)), "SetToken.constructor: Invalid natural unit" ); factory = _factory; naturalUnit = _naturalUnit; } /* ============ Public Functions ============ */ /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external { // Check that function caller is Core require( msg.sender == ISetFactory(factory).core(), "SetToken.mint: Sender must be core" ); _mint(_issuer, _quantity); } /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external { // Check that function caller is Core require( msg.sender == ISetFactory(factory).core(), "SetToken.burn: Sender must be core" ); _burn(_from, _quantity); } /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory) { return components; } /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory) { return units; } /* * Validates address is member of Set's components * * @param _tokenAddress Address of token being checked * @return bool Whether token is member of Set's components */ function tokenIsComponent( address _tokenAddress ) public view returns (bool) { return isComponent[_tokenAddress]; } }
File 5 of 10: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.4.18; contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */
File 6 of 10: CoreIssuanceLibrary
// File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/core/interfaces/IVault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IVault * @author Set Protocol * * The IVault interface provides a light-weight, structured way to interact with the Vault * contract from another contract. */ interface IVault { /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) external; /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) external; /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external; /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256); } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/core/lib/CoreIssuanceLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; /** * @title CoreIssuanceLibrary * @author Set Protocol * * This library contains functions for calculating deposit, withdrawal,and transfer quantities */ library CoreIssuanceLibrary { using SafeMath for uint256; /** * Calculate the quantities required to deposit and decrement during issuance. Takes into account * the tokens an owner already has in the vault. * * @param _components Addresses of components * @param _componentQuantities Component quantities to increment and withdraw * @param _owner Address to deposit and decrement quantities from * @param _vault Address to vault * @return uint256[] decrementQuantities Quantities to decrement from vault * @return uint256[] depositQuantities Quantities to deposit into the vault */ function calculateDepositAndDecrementQuantities( address[] calldata _components, uint256[] calldata _componentQuantities, address _owner, address _vault ) external view returns ( uint256[] memory /* decrementQuantities */, uint256[] memory /* depositQuantities */ ) { uint256 componentCount = _components.length; uint256[] memory decrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory depositQuantities = new uint256[](componentCount); for (uint256 i = 0; i < componentCount; i++) { // Fetch component quantity in vault uint256 vaultBalance = IVault(_vault).getOwnerBalance( _components[i], _owner ); // If the vault holds enough components, decrement the full amount if (vaultBalance >= _componentQuantities[i]) { decrementTokenOwnerValues[i] = _componentQuantities[i]; } else { // User has less than required amount, decrement the vault by full balance if (vaultBalance > 0) { decrementTokenOwnerValues[i] = vaultBalance; } depositQuantities[i] = _componentQuantities[i].sub(vaultBalance); } } return ( decrementTokenOwnerValues, depositQuantities ); } /** * Calculate the quantities required to withdraw and increment during redeem and withdraw. Takes into * account a bitmask exclusion parameter. * * @param _componentQuantities Component quantities to increment and withdraw * @param _toExclude Mask of indexes of tokens to exclude from withdrawing * @return uint256[] incrementQuantities Quantities to increment in vault * @return uint256[] withdrawQuantities Quantities to withdraw from vault */ function calculateWithdrawAndIncrementQuantities( uint256[] calldata _componentQuantities, uint256 _toExclude ) external pure returns ( uint256[] memory /* incrementQuantities */, uint256[] memory /* withdrawQuantities */ ) { uint256 componentCount = _componentQuantities.length; uint256[] memory incrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory withdrawToValues = new uint256[](componentCount); // Loop through and decrement vault balances for the set, withdrawing if requested for (uint256 i = 0; i < componentCount; i++) { // Calculate bit index of current component uint256 componentBitIndex = CommonMath.safePower(2, i); // Transfer to user unless component index is included in _toExclude if ((_toExclude & componentBitIndex) != 0) { incrementTokenOwnerValues[i] = _componentQuantities[i]; } else { withdrawToValues[i] = _componentQuantities[i]; } } return ( incrementTokenOwnerValues, withdrawToValues ); } /** * Calculate the required component quantities required for issuance or rdemption for a given * quantity of Set Tokens * * @param _componentUnits The units of the component token * @param _naturalUnit The natural unit of the Set token * @param _quantity The number of tokens being redeem * @return uint256[] Required quantities in base units of components */ function calculateRequiredComponentQuantities( uint256[] calldata _componentUnits, uint256 _naturalUnit, uint256 _quantity ) external pure returns (uint256[] memory) { require( _quantity.mod(_naturalUnit) == 0, "CoreIssuanceLibrary: Quantity must be a multiple of nat unit" ); uint256[] memory tokenValues = new uint256[](_componentUnits.length); // Transfer the underlying tokens to the corresponding token balances for (uint256 i = 0; i < _componentUnits.length; i++) { tokenValues[i] = _quantity.div(_naturalUnit).mul(_componentUnits[i]); } return tokenValues; } }
File 7 of 10: SetTokenFactory
// File: contracts/lib/Bytes32Library.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library Bytes32Library { /** * Converts a bytes32 data structure into a bytes array. * * @param data Piece of data encoded as bytes32 * @return bytes */ function bytes32ToBytes(bytes32 data) internal pure returns (bytes memory) { uint256 i = 0; while (i < 32 && uint256(bytes32(data[i])) != 0) { ++i; } bytes memory result = new bytes(i); i = 0; while (i < 32 && data[i] != 0) { result[i] = data[i]; ++i; } return result; } /** * Converts a piece of data encoded as bytes32 into a string. * * @param data Piece of data encoded as bytes32 * @return string */ function bytes32ToString(bytes32 data) internal pure returns (string memory) { bytes memory intermediate = bytes32ToBytes(data); return string(abi.encodePacked(intermediate)); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @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. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; 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 _allowed[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, _allowed[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 _allowed[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, _allowed[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 _allowed[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, _allowed[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)); _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)); _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)); _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(spender != address(0)); require(owner != address(0)); _allowed[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, _allowed[account][msg.sender].sub(value)); } } // File: contracts/lib/CommonValidationsLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonValidationsLibrary { /** * Ensures that an address array is not empty. * * @param _addressArray Address array input */ function validateNonEmpty( address[] calldata _addressArray ) external pure { require( _addressArray.length > 0, "Address array length must be > 0" ); } /** * Ensures that an address array and uint256 array are equal length * * @param _addressArray Address array input * @param _uint256Array Uint256 array input */ function validateEqualLength( address[] calldata _addressArray, uint256[] calldata _uint256Array ) external pure { require( _addressArray.length == _uint256Array.length, "Input length mismatch" ); } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/tokens/SetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title SetToken * @author Set Protocol * * Implementation of the basic Set token. */ contract SetToken is ERC20, ERC20Detailed { using SafeMath for uint256; /* ============ State Variables ============ */ uint256 public naturalUnit; address[] public components; uint256[] public units; // Mapping of componentHash to isComponent mapping(address => bool) internal isComponent; // Address of the Factory contract that created the SetToken address public factory; /* ============ Constructor ============ */ /** * Constructor function for Set token * * As looping operations are expensive, checking for duplicates will be on the onus of the application developer * * @param _factory The factory used to create the Set Token * @param _components A list of component address which you want to include * @param _units A list of quantities of each component (corresponds to the Set of _components) * @param _naturalUnit The minimum multiple of Sets that can be issued or redeemed * @param _name The Set's name * @param _symbol The Set's symbol */ constructor( address _factory, address[] memory _components, uint256[] memory _units, uint256 _naturalUnit, string memory _name, string memory _symbol ) public ERC20Detailed( _name, _symbol, 18 ) { // Storing count and unit counts to local variable to save on invocation uint256 unitCount = _units.length; // Require naturalUnit passed is greater than 0 require( _naturalUnit > 0, "SetToken.constructor: Natural unit must be positive" ); // Confirm an empty _components array is not passed CommonValidationsLibrary.validateNonEmpty(_components); // Confirm there is one quantity for every token address CommonValidationsLibrary.validateEqualLength(_components, _units); // NOTE: It will be the onus of developers to check whether the addressExists // are in fact ERC20 addresses uint8 minDecimals = 18; uint8 currentDecimals; for (uint256 i = 0; i < unitCount; i++) { // Check that all units are non-zero uint256 currentUnits = _units[i]; require( currentUnits > 0, "SetToken.constructor: Units must be positive" ); // Check that all addresses are non-zero address currentComponent = _components[i]; require( currentComponent != address(0), "SetToken.constructor: Invalid component address" ); // Figure out which of the components has the minimum decimal value /* solium-disable-next-line security/no-low-level-calls */ (bool success, ) = currentComponent.call(abi.encodeWithSignature("decimals()")); if (success) { currentDecimals = ERC20Detailed(currentComponent).decimals(); minDecimals = currentDecimals < minDecimals ? currentDecimals : minDecimals; } else { // If one of the components does not implement decimals, we assume the worst // and set minDecimals to 0 minDecimals = 0; } // Check the component has not already been added require( !tokenIsComponent(currentComponent), "SetToken.constructor: Duplicated component" ); // Add component to isComponent mapping isComponent[currentComponent] = true; // Add component data to components and units state variables components.push(currentComponent); units.push(currentUnits); } // This is the minimum natural unit possible for a Set with these components. require( _naturalUnit >= CommonMath.safePower(10, uint256(18).sub(minDecimals)), "SetToken.constructor: Invalid natural unit" ); factory = _factory; naturalUnit = _naturalUnit; } /* ============ Public Functions ============ */ /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external { // Check that function caller is Core require( msg.sender == ISetFactory(factory).core(), "SetToken.mint: Sender must be core" ); _mint(_issuer, _quantity); } /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external { // Check that function caller is Core require( msg.sender == ISetFactory(factory).core(), "SetToken.burn: Sender must be core" ); _burn(_from, _quantity); } /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory) { return components; } /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory) { return units; } /* * Validates address is member of Set's components * * @param _tokenAddress Address of token being checked * @return bool Whether token is member of Set's components */ function tokenIsComponent( address _tokenAddress ) public view returns (bool) { return isComponent[_tokenAddress]; } } // File: contracts/core/tokens/SetTokenFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title SetTokenFactory * @author Set Protocol * * SetTokenFactory is a smart contract used to deploy new SetToken contracts. * SetTokens deployed by the factory can only have their mint and burn functions * called by Core */ contract SetTokenFactory { using Bytes32Library for bytes32; /* ============ State Variables ============ */ // Address of the Core contract address public core; /* ============ Constructor ============ */ /** * Set core constructor * * @param _core The address of deployed core contract */ constructor( address _core ) public { core = _core; } /* ============ Public Functions ============ */ /** * Deploys a new SetToken contract. * Can only be called by authorized core contracts. * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * -- Unused callData param used to pass additional information to factories -- * @return setToken The address of the newly created SetToken */ function createSet( address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata ) external returns (address) { // Expecting caller to be Core require( msg.sender == core, "SetTokenFactory.create: Sender must be core" ); // Create a new SetToken contract return address( new SetToken( address(this), _components, _units, _naturalUnit, _name.bytes32ToString(), _symbol.bytes32ToString() ) ); } }
File 8 of 10: AddressToAddressWhiteList
pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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); 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); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/lib/TimeLockUpgradeV2.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title TimeLockUpgradeV2 * @author Set Protocol * * The TimeLockUpgradeV2 contract contains a modifier for handling minimum time period updates * * CHANGELOG: * - Requires that the caller is the owner * - New function to allow deletion of existing timelocks * - Added upgradeData to UpgradeRegistered event */ contract TimeLockUpgradeV2 is Ownable { using SafeMath for uint256; /* ============ State Variables ============ */ // Timelock Upgrade Period in seconds uint256 public timeLockPeriod; // Mapping of maps hash of registered upgrade to its registration timestam mapping(bytes32 => uint256) public timeLockedUpgrades; /* ============ Events ============ */ event UpgradeRegistered( bytes32 indexed _upgradeHash, uint256 _timestamp, bytes _upgradeData ); event RemoveRegisteredUpgrade( bytes32 indexed _upgradeHash ); /* ============ Modifiers ============ */ modifier timeLockUpgrade() { require( isOwner(), "TimeLockUpgradeV2: The caller must be the owner" ); // If the time lock period is 0, then allow non-timebound upgrades. // This is useful for initialization of the protocol and for testing. if (timeLockPeriod > 0) { // The upgrade hash is defined by the hash of the transaction call data, // which uniquely identifies the function as well as the passed in arguments. bytes32 upgradeHash = keccak256( abi.encodePacked( msg.data ) ); uint256 registrationTime = timeLockedUpgrades[upgradeHash]; // If the upgrade hasn't been registered, register with the current time. if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp, msg.data ); return; } require( block.timestamp >= registrationTime.add(timeLockPeriod), "TimeLockUpgradeV2: Time lock period must have elapsed." ); // Reset the timestamp to 0 timeLockedUpgrades[upgradeHash] = 0; } // Run the rest of the upgrades _; } /* ============ Function ============ */ /** * Removes an existing upgrade. * * @param _upgradeHash Keccack256 hash that uniquely identifies function called and arguments */ function removeRegisteredUpgrade( bytes32 _upgradeHash ) external onlyOwner { require( timeLockedUpgrades[_upgradeHash] != 0, "TimeLockUpgradeV2.removeRegisteredUpgrade: Upgrade hash must be registered" ); // Reset the timestamp to 0 timeLockedUpgrades[_upgradeHash] = 0; emit RemoveRegisteredUpgrade( _upgradeHash ); } /** * Change timeLockPeriod period. Generally called after initially settings have been set up. * * @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution */ function setTimeLockPeriod( uint256 _timeLockPeriod ) external onlyOwner { // Only allow setting of the timeLockPeriod if the period is greater than the existing require( _timeLockPeriod > timeLockPeriod, "TimeLockUpgradeV2: New period must be greater than existing" ); timeLockPeriod = _timeLockPeriod; } } // File: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } } // File: contracts/lib/AddressToAddressWhiteList.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title AddressToAddressWhiteList * @author Set Protocol * * WhiteList that matches addresses to other addresses */ contract AddressToAddressWhiteList is TimeLockUpgradeV2 { using AddressArrayUtils for address[]; /* ============ State Variables ============ */ address[] public keys; mapping(address => address) public whitelist; /* ============ Events ============ */ event PairAdded( address indexed key, address value ); event PairRemoved( address indexed key, address value ); /* ============ Constructor ============ */ /** * Constructor function for AddressToAddressWhiteList * * Allow initial addresses to be passed in so a separate transaction is not required for each. * Each key type address passed is matched with a corresponding value type token address at the same index. * The _initialKeys and _initialValues arrays must be equal length. * * @param _initialKeys Starting set of key type addresses to whitelist * @param _initialValues Starting set of value type addresses to whitelist */ constructor( address[] memory _initialKeys, address[] memory _initialValues ) public { require( _initialKeys.length == _initialValues.length, "AddressToAddressWhiteList.constructor: Address array lengths must match." ); // Add each of initial addresses to state for (uint256 i = 0; i < _initialKeys.length; i++) { address keyTypeAddressToAdd = _initialKeys[i]; // Require keys are unique require( whitelist[keyTypeAddressToAdd] == address(0), "AddressToAddressWhiteList.constructor: Key must be unique." ); // Require values are non zero addresses require( _initialValues[i] != address(0), "AddressToAddressWhiteList.constructor: Value must be non zero." ); keys.push(keyTypeAddressToAdd); whitelist[keyTypeAddressToAdd] = _initialValues[i]; } } /* ============ External Functions ============ */ /** * Add an address to the whitelist * * @param _key Key type address to add to the whitelist * @param _value Value type address to add to the whitelist under _key */ function addPair( address _key, address _value ) external timeLockUpgrade { require( whitelist[_key] == address(0), "AddressToAddressWhiteList.addPair: Address pair already exists." ); require( _value != address(0), "AddressToAddressWhiteList.addPair: Value must be non zero." ); keys.push(_key); whitelist[_key] = _value; emit PairAdded(_key, _value); } /** * Remove a address to address pair from the whitelist * * @param _key Key type address to remove to the whitelist */ function removePair( address _key ) external timeLockUpgrade { address valueToRemove = whitelist[_key]; require( valueToRemove != address(0), "AddressToAddressWhiteList.removePair: key type address is not current whitelisted." ); keys = keys.remove(_key); whitelist[_key] = address(0); emit PairRemoved(_key, valueToRemove); } /** * Edit value type address associated with a key * * @param _key Key type address to add to the whitelist * @param _value Value type address to add to the whitelist under _key */ function editPair( address _key, address _value ) external timeLockUpgrade { require( whitelist[_key] != address(0), "AddressToAddressWhiteList.editPair: Address pair must exist." ); require( _value != address(0), "AddressToAddressWhiteList.editPair: New value must be non zero." ); emit PairRemoved( _key, whitelist[_key] ); // Set new value type address for passed key type address whitelist[_key] = _value; emit PairAdded( _key, _value ); } /** * Return array of all whitelisted addresses * * @return address[] Array of key type addresses */ function validAddresses() external view returns (address[] memory) { return keys; } /** * Return array of value type addresses based on passed in key type addresses * * @param _key Array of key type addresses to get value type addresses for * @return address[] Array of value type addresses */ function getValues( address[] calldata _key ) external view returns (address[] memory) { // Get length of passed array uint256 arrayLength = _key.length; // Instantiate value type addresses array address[] memory values = new address[](arrayLength); for (uint256 i = 0; i < arrayLength; i++) { // Get value type address for key type address at index i values[i] = getValue( _key[i] ); } return values; } /** * Return value type address associated with a passed key type address * * @param _key Address of key type * @return address Address associated with _key */ function getValue( address _key ) public view returns (address) { // Require key to have matching value type address require( whitelist[_key] != address(0), "AddressToAddressWhiteList.getValue: No value for that address." ); // Return address associated with key return whitelist[_key]; } /** * Verifies an array of addresses against the whitelist * * @param _keys Array of key type addresses to check if value exists * @return bool Whether all addresses in the list are whitelisted */ function areValidAddresses( address[] calldata _keys ) external view returns (bool) { // Get length of passed array uint256 arrayLength = _keys.length; for (uint256 i = 0; i < arrayLength; i++) { // Return false if key type address doesn't have matching value type address if (whitelist[_keys[i]] == address(0)) { return false; } } return true; } }
File 9 of 10: CommonValidationsLibrary
/* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonValidationsLibrary { /** * Ensures that an address array is not empty. * * @param _addressArray Address array input */ function validateNonEmpty( address[] calldata _addressArray ) external pure { require( _addressArray.length > 0, "Address array length must be > 0" ); } /** * Ensures that an address array and uint256 array are equal length * * @param _addressArray Address array input * @param _uint256Array Uint256 array input */ function validateEqualLength( address[] calldata _addressArray, uint256[] calldata _uint256Array ) external pure { require( _addressArray.length == _uint256Array.length, "Input length mismatch" ); } }
File 10 of 10: ERC20Wrapper
{"CommonMath.sol":{"content":"/*\r\n Copyright 2018 Set Labs Inc.\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n*/\r\n\r\npragma solidity 0.5.7;\r\n\r\nimport \"./SafeMath.sol\";\r\n\r\n\r\nlibrary CommonMath {\r\n using SafeMath for uint256;\r\n\r\n /**\r\n * Calculates and returns the maximum value for a uint256\r\n *\r\n * @return The maximum value for uint256\r\n */\r\n function maxUInt256()\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n return 2 ** 256 - 1;\r\n }\r\n\r\n /**\r\n * @dev Performs the power on a specified value, reverts on overflow.\r\n */\r\n function safePower(\r\n uint256 a,\r\n uint256 pow\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n require(a \u003e 0);\r\n\r\n uint256 result = 1;\r\n for (uint256 i = 0; i \u003c pow; i++){\r\n uint256 previousResult = result;\r\n\r\n // Using safemath multiplication prevents overflows\r\n result = previousResult.mul(a);\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Checks for rounding errors and returns value of potential partial amounts of a principal\r\n *\r\n * @param _principal Number fractional amount is derived from\r\n * @param _numerator Numerator of fraction\r\n * @param _denominator Denominator of fraction\r\n * @return uint256 Fractional amount of principal calculated\r\n */\r\n function getPartialAmount(\r\n uint256 _principal,\r\n uint256 _numerator,\r\n uint256 _denominator\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n // Get remainder of partial amount (if 0 not a partial amount)\r\n uint256 remainder = mulmod(_principal, _numerator, _denominator);\r\n\r\n // Return if not a partial amount\r\n if (remainder == 0) {\r\n return _principal.mul(_numerator).div(_denominator);\r\n }\r\n\r\n // Calculate error percentage\r\n uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal));\r\n\r\n // Require error percentage is less than 0.1%.\r\n require(\r\n errPercentageTimes1000000 \u003c 1000,\r\n \"CommonMath.getPartialAmount: Rounding error exceeds bounds\"\r\n );\r\n\r\n return _principal.mul(_numerator).div(_denominator);\r\n }\r\n\r\n}\r\n\r\n"},"ERC20Wrapper.sol":{"content":"/*\r\n Copyright 2018 Set Labs Inc.\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n*/\r\n\r\npragma solidity 0.5.7;\r\n\r\nimport \"./CommonMath.sol\";\r\nimport \"./IERC20.sol\";\r\n\r\n\r\n/**\r\n * @title ERC20Wrapper\r\n * @author Set Protocol\r\n *\r\n * This library contains functions for interacting wtih ERC20 tokens, even those not fully compliant.\r\n * For all functions we will only accept tokens that return a null or true value, any other values will\r\n * cause the operation to revert.\r\n */\r\nlibrary ERC20Wrapper {\r\n\r\n // ============ Internal Functions ============\r\n\r\n /**\r\n * Check balance owner\u0027s balance of ERC20 token\r\n *\r\n * @param _token The address of the ERC20 token\r\n * @param _owner The owner who\u0027s balance is being checked\r\n * @return uint256 The _owner\u0027s amount of tokens\r\n */\r\n function balanceOf(\r\n address _token,\r\n address _owner\r\n )\r\n external\r\n view\r\n returns (uint256)\r\n {\r\n return IERC20(_token).balanceOf(_owner);\r\n }\r\n\r\n /**\r\n * Checks spender\u0027s allowance to use token\u0027s on owner\u0027s behalf.\r\n *\r\n * @param _token The address of the ERC20 token\r\n * @param _owner The token owner address\r\n * @param _spender The address the allowance is being checked on\r\n * @return uint256 The spender\u0027s allowance on behalf of owner\r\n */\r\n function allowance(\r\n address _token,\r\n address _owner,\r\n address _spender\r\n )\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n return IERC20(_token).allowance(_owner, _spender);\r\n }\r\n\r\n /**\r\n * Transfers tokens from an address. Handle\u0027s tokens that return true or null.\r\n * If other value returned, reverts.\r\n *\r\n * @param _token The address of the ERC20 token\r\n * @param _to The address to transfer to\r\n * @param _quantity The amount of tokens to transfer\r\n */\r\n function transfer(\r\n address _token,\r\n address _to,\r\n uint256 _quantity\r\n )\r\n external\r\n {\r\n IERC20(_token).transfer(_to, _quantity);\r\n\r\n // Check that transfer returns true or null\r\n require(\r\n checkSuccess(),\r\n \"ERC20Wrapper.transfer: Bad return value\"\r\n );\r\n }\r\n\r\n /**\r\n * Transfers tokens from an address (that has set allowance on the proxy).\r\n * Handle\u0027s tokens that return true or null. If other value returned, reverts.\r\n *\r\n * @param _token The address of the ERC20 token\r\n * @param _from The address to transfer from\r\n * @param _to The address to transfer to\r\n * @param _quantity The number of tokens to transfer\r\n */\r\n function transferFrom(\r\n address _token,\r\n address _from,\r\n address _to,\r\n uint256 _quantity\r\n )\r\n external\r\n {\r\n IERC20(_token).transferFrom(_from, _to, _quantity);\r\n\r\n // Check that transferFrom returns true or null\r\n require(\r\n checkSuccess(),\r\n \"ERC20Wrapper.transferFrom: Bad return value\"\r\n );\r\n }\r\n\r\n /**\r\n * Grants spender ability to spend on owner\u0027s behalf.\r\n * Handle\u0027s tokens that return true or null. If other value returned, reverts.\r\n *\r\n * @param _token The address of the ERC20 token\r\n * @param _spender The address to approve for transfer\r\n * @param _quantity The amount of tokens to approve spender for\r\n */\r\n function approve(\r\n address _token,\r\n address _spender,\r\n uint256 _quantity\r\n )\r\n internal\r\n {\r\n IERC20(_token).approve(_spender, _quantity);\r\n\r\n // Check that approve returns true or null\r\n require(\r\n checkSuccess(),\r\n \"ERC20Wrapper.approve: Bad return value\"\r\n );\r\n }\r\n\r\n /**\r\n * Ensure\u0027s the owner has granted enough allowance for system to\r\n * transfer tokens.\r\n *\r\n * @param _token The address of the ERC20 token\r\n * @param _owner The address of the token owner\r\n * @param _spender The address to grant/check allowance for\r\n * @param _quantity The amount to see if allowed for\r\n */\r\n function ensureAllowance(\r\n address _token,\r\n address _owner,\r\n address _spender,\r\n uint256 _quantity\r\n )\r\n internal\r\n {\r\n uint256 currentAllowance = allowance(_token, _owner, _spender);\r\n if (currentAllowance \u003c _quantity) {\r\n approve(\r\n _token,\r\n _spender,\r\n CommonMath.maxUInt256()\r\n );\r\n }\r\n }\r\n\r\n // ============ Private Functions ============\r\n\r\n /**\r\n * Checks the return value of the previous function up to 32 bytes. Returns true if the previous\r\n * function returned 0 bytes or 1.\r\n */\r\n function checkSuccess(\r\n )\r\n private\r\n pure\r\n returns (bool)\r\n {\r\n // default to failure\r\n uint256 returnValue = 0;\r\n\r\n assembly {\r\n // check number of bytes returned from last function call\r\n switch returndatasize\r\n\r\n // no bytes returned: assume success\r\n case 0x0 {\r\n returnValue := 1\r\n }\r\n\r\n // 32 bytes returned\r\n case 0x20 {\r\n // copy 32 bytes into scratch space\r\n returndatacopy(0x0, 0x0, 0x20)\r\n\r\n // load those bytes into returnValue\r\n returnValue := mload(0x0)\r\n }\r\n\r\n // not sure what was returned: dont mark as success\r\n default { }\r\n }\r\n\r\n // check if returned value is one or nothing\r\n return returnValue == 1;\r\n }\r\n}\r\n"},"IERC20.sol":{"content":"/*\r\n Copyright 2018 Set Labs Inc.\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n*/\r\n\r\npragma solidity 0.5.7;\r\n\r\n\r\n/**\r\n * @title IERC20\r\n * @author Set Protocol\r\n *\r\n * Interface for using ERC20 Tokens. This interface is needed to interact with tokens that are not\r\n * fully ERC20 compliant and return something other than true on successful transfers.\r\n */\r\ninterface IERC20 {\r\n function balanceOf(\r\n address _owner\r\n )\r\n external\r\n view\r\n returns (uint256);\r\n\r\n function allowance(\r\n address _owner,\r\n address _spender\r\n )\r\n external\r\n view\r\n returns (uint256);\r\n\r\n function transfer(\r\n address _to,\r\n uint256 _quantity\r\n )\r\n external;\r\n\r\n function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _quantity\r\n )\r\n external;\r\n\r\n function approve(\r\n address _spender,\r\n uint256 _quantity\r\n )\r\n external\r\n returns (bool);\r\n}\r\n"},"SafeMath.sol":{"content":"pragma solidity ^0.5.7;\r\n\r\n/**\r\n * @title SafeMath\r\n * @dev Unsigned math operations with safety checks that revert on error.\r\n */\r\nlibrary SafeMath {\r\n /**\r\n * @dev Multiplies two unsigned integers, reverts on overflow.\r\n */\r\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\r\n // benefit is lost if \u0027b\u0027 is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b);\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.\r\n */\r\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b \u003e 0);\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn\u0027t hold\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).\r\n */\r\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\r\n require(b \u003c= a);\r\n uint256 c = a - b;\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Adds two unsigned integers, reverts on overflow.\r\n */\r\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\r\n uint256 c = a + b;\r\n require(c \u003e= a);\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),\r\n * reverts when dividing by zero.\r\n */\r\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\r\n require(b != 0);\r\n return a % b;\r\n }\r\n}\r\n"}}