Transaction Hash:
Block:
10764631 at Aug-30-2020 09:28:21 PM +UTC
Transaction Fee:
0.053453058 ETH
$111.36
Gas Used:
387,341 Gas / 138 Gwei
Emitted Events:
| 88 |
WETH9.Deposit( dst=OneSplit, wad=974118265984000000 )
|
| 89 |
WETH9.Transfer( src=OneSplit, dst=UniswapV2Pair, wad=974118265984000000 )
|
| 90 |
YFV.Transfer( from=UniswapV2Pair, to=OneSplit, value=8894934969450818536 )
|
| 91 |
UniswapV2Pair.Sync( reserve0=4786693409439105043068, reserve1=523610549371391462819 )
|
| 92 |
UniswapV2Pair.Swap( sender=OneSplit, amount0In=0, amount1In=974118265984000000, amount0Out=8894934969450818536, amount1Out=0, to=OneSplit )
|
| 93 |
YFV.Transfer( from=OneSplit, to=OneSplitWrap, value=8894934969450818536 )
|
| 94 |
YFV.Transfer( from=OneSplitWrap, to=0x1f8A6d8185b76F5ac08f335610a2390DAb3225a8, value=8894934969450818536 )
|
| 95 |
YFV.Transfer( from=0x1f8A6d8185b76F5ac08f335610a2390DAb3225a8, to=[Receiver] OneInchExchange, value=8780781873361845350 )
|
| 96 |
YFV.Transfer( from=0x1f8A6d8185b76F5ac08f335610a2390DAb3225a8, to=0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5, value=114153096088973186 )
|
| 97 |
ChiToken.Transfer( from=[Sender] 0x617f9df5aa1e40283113c918921fc287222a1d80, to=0x0000000000000000000000000000000000000000, value=0 )
|
| 98 |
ChiToken.Approval( owner=[Sender] 0x617f9df5aa1e40283113c918921fc287222a1d80, spender=0x715d6aed40d999e564b238d5bfc17ff2e953e7d9, value=0 )
|
| 99 |
ChiToken.Transfer( from=0xc2Ffe6EC03EBC81E0F39FCA0B76e0baaE4F2195e, to=0x0000000000000000000000000000000000000000, value=0 )
|
| 100 |
YFV.Transfer( from=[Receiver] OneInchExchange, to=[Sender] 0x617f9df5aa1e40283113c918921fc287222a1d80, value=8780781873361845350 )
|
| 101 |
OneInchExchange.History( sender=[Sender] 0x617f9df5aa1e40283113c918921fc287222a1d80, fromToken=0xEeeeeEee...eeeeeEEeE, toToken=YFV, fromAmount=974118265984000000, toAmount=8780781873361845350 )
|
| 102 |
OneInchExchange.Swapped( fromToken=0xEeeeeEee...eeeeeEEeE, toToken=YFV, referrer=0x0000000000000000000000000000000000000000, fromAmount=974118265984000000, toAmount=8780781873361845350, referrerFee=0, fee=0 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x45f24BaE...9702BCDfa | |||||
| 0x617F9df5...7222a1d80 |
1.112118265984 Eth
Nonce: 1
|
0.084546942 Eth
Nonce: 2
| 1.027571323984 | ||
| 0xC02aaA39...83C756Cc2 | 4,342,320.220662018602169965 Eth | 4,342,321.194780284586169965 Eth | 0.974118265984 | ||
|
0xC4aEb207...332b9BC77
Miner
| (Easy2Mine) | 1,069.730732938823434081 Eth | 1,069.784185996823434081 Eth | 0.053453058 | |
| 0xcB4f983E...138115F0b |
Execution Trace
ETH 0.974118265984
OneInchExchange.swap( fromToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, toToken=0x45f24BaEef268BB6d63AEe5129015d69702BCDfa, fromTokenAmount=974118265984000000, minReturnAmount=8692974054628226896, guaranteedAmount=8780781873361845350, referrer=0x0000000000000000000000000000000000000000, callAddresses=[0x1f8A6d8185b76F5ac08f335610a2390DAb3225a8], callDataConcat=0x47178854000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE00000000000000000000000045F24BAEEF268BB6D63AEE5129015D69702BCDFA0000000000000000000000000000000000000000000000000D84C366DD32200000000000000000000000000000000000000000000000000078A3A5D867CD775000000000000000000000000000000000000000000000000079DB9A975BEBFC6600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000006E0000000000000000000000000000000000000000000000000000000000000074000000000000000000000000000000000000000000000000000000000000000010000000000000000000000006CB2291A3C3794FCA0F5B6E34A8E6EA7933CA6670000000000000000000000000000000000000000000000000000000000000524E2A7515E000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE00000000000000000000000045F24BAEEF268BB6D63AEE5129015D69702BCDFA0000000000000000000000000000000000000000000000000D84C366DD322000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000052400000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000D84C366DD322000, starts=[0, 1924], gasLimitsAndValues=[974118265984000000] ) => ( returnAmount=8780781873361845350 )
ETH 0.974118265984
0x1f8a6d8185b76f5ac08f335610a2390dab3225a8.47178854( )-
ChiToken.STATICCALL( )
-
GasToken2.STATICCALL( )
ETH 0.974118265984
OneSplitWrap.swap( fromToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, destToken=0x45f24BaEef268BB6d63AEe5129015d69702BCDfa, amount=974118265984000000, minReturn=1, distribution=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], flags=0 ) => ( returnAmount=8894934969450818536 )-
MooniFactory.isPool( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( False ) -
MooniFactory.isPool( 0x45f24BaEef268BB6d63AEe5129015d69702BCDfa ) => ( False ) -
DmmController.getUnderlyingTokenForDmm( dmmToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( 0x0000000000000000000000000000000000000000 ) -
DmmController.getUnderlyingTokenForDmm( dmmToken=0x45f24BaEef268BB6d63AEe5129015d69702BCDfa ) => ( 0x0000000000000000000000000000000000000000 ) -
CompoundRegistry.tokenByCToken( cToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( 0x0000000000000000000000000000000000000000 ) -
CompoundRegistry.tokenByCToken( cToken=0x45f24BaEef268BB6d63AEe5129015d69702BCDfa ) => ( 0x0000000000000000000000000000000000000000 ) -
YFV.STATICCALL( )
-
AaveRegistry.tokenByAToken( aToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( 0x0000000000000000000000000000000000000000 ) -
AaveRegistry.tokenByAToken( aToken=0x45f24BaEef268BB6d63AEe5129015d69702BCDfa ) => ( 0x0000000000000000000000000000000000000000 ) ETH 0.974118265984
OneSplit.swap( fromToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, destToken=0x45f24BaEef268BB6d63AEe5129015d69702BCDfa, amount=974118265984000000, minReturn=0, distribution=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], flags=0 ) => ( returnAmount=8894934969450818536 )- ETH 0.974118265984
WETH9.CALL( )
-
UniswapV2Factory.getPair( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0x45f24BaEef268BB6d63AEe5129015d69702BCDfa ) => ( 0xcB4f983E705caeb7217c5C3785001Cb138115F0b ) -
WETH9.balanceOf( 0xcB4f983E705caeb7217c5C3785001Cb138115F0b ) => ( 522636431105407462819 )
-
YFV.balanceOf( account=0xcB4f983E705caeb7217c5C3785001Cb138115F0b ) => ( 4795588344408555861604 )
-
UniswapV2Pair.STATICCALL( )
-
WETH9.transfer( dst=0xcB4f983E705caeb7217c5C3785001Cb138115F0b, wad=974118265984000000 ) => ( True )
UniswapV2Pair.swap( amount0Out=8894934969450818536, amount1Out=0, to=0x480ea104fF7063Ed0Af41c98d8EF2457afE2a41c, data=0x )
-
YFV.balanceOf( account=0x480ea104fF7063Ed0Af41c98d8EF2457afE2a41c ) => ( 8894934969450818536 )
-
YFV.transfer( recipient=0x6cb2291A3c3794fcA0F5b6E34a8E6eA7933CA667, amount=8894934969450818536 ) => ( True )
- ETH 0.974118265984
-
YFV.balanceOf( account=0x6cb2291A3c3794fcA0F5b6E34a8E6eA7933CA667 ) => ( 8894934969450818536 )
-
YFV.transfer( recipient=0x1f8A6d8185b76F5ac08f335610a2390DAb3225a8, amount=8894934969450818536 ) => ( True )
-
-
YFV.balanceOf( account=0x1f8A6d8185b76F5ac08f335610a2390DAb3225a8 ) => ( 8894934969450818536 )
-
YFV.transfer( recipient=0x11111254369792b2Ca5d084aB5eEA397cA8fa48B, amount=8780781873361845350 ) => ( True )
-
YFV.transfer( recipient=0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5, amount=114153096088973186 ) => ( True )
-
ChiToken.STATICCALL( )
-
GasToken2.STATICCALL( )
0x715d6aed40d999e564b238d5bfc17ff2e953e7d9.17484c2e( )-
ChiToken.freeFromUpTo( from=0x617F9df5aa1e40283113c918921Fc287222a1d80, value=10 ) => ( 0 )
-
0xc2ffe6ec03ebc81e0f39fca0b76e0baae4f2195e.17484c2e( )-
ChiToken.freeUpTo( value=10 ) => ( 0 )
-
-
-
YFV.balanceOf( account=0x11111254369792b2Ca5d084aB5eEA397cA8fa48B ) => ( 8780781873361845350 )
-
YFV.transfer( recipient=0x617F9df5aa1e40283113c918921Fc287222a1d80, amount=8780781873361845350 ) => ( True )
TokenSpender.burnGasToken( gasSpent=476338 )-
GasToken2.freeUpTo( value=11 ) => ( freed=0 )
-
swap[OneInchExchange (ln:766)]
gasleft[OneInchExchange (ln:783)]claimTokens[OneInchExchange (ln:789)]externalCall[OneInchExchange (ln:794)]universalTransfer[OneInchExchange (ln:804)]universalBalanceOf[OneInchExchange (ln:804)]universalBalanceOf[OneInchExchange (ln:806)]_handleFees[OneInchExchange (ln:807)]div[OneInchExchange (ln:849)]mul[OneInchExchange (ln:849)]sub[OneInchExchange (ln:849)]div[OneInchExchange (ln:852)]universalTransfer[OneInchExchange (ln:853)]sub[OneInchExchange (ln:854)]sub[OneInchExchange (ln:855)]universalTransfer[OneInchExchange (ln:861)]owner[OneInchExchange (ln:861)]sub[OneInchExchange (ln:862)]
universalTransfer[OneInchExchange (ln:810)]History[OneInchExchange (ln:812)]Swapped[OneInchExchange (ln:820)]sub[OneInchExchange (ln:827)]burnGasToken[OneInchExchange (ln:830)]sub[OneInchExchange (ln:830)]gasleft[OneInchExchange (ln:830)]
File 1 of 14: OneInchExchange
File 2 of 14: WETH9
File 3 of 14: OneSplit
File 4 of 14: UniswapV2Pair
File 5 of 14: YFV
File 6 of 14: OneSplitWrap
File 7 of 14: ChiToken
File 8 of 14: GasToken2
File 9 of 14: MooniFactory
File 10 of 14: DmmController
File 11 of 14: CompoundRegistry
File 12 of 14: AaveRegistry
File 13 of 14: UniswapV2Factory
File 14 of 14: TokenSpender
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
library ExternalCall {
// Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function externalCall(address destination, uint value, bytes memory data, uint dataOffset, uint dataLength, uint gasLimit) internal returns(bool result) {
// solium-disable-next-line security/no-inline-assembly
if (gasLimit == 0) {
gasLimit = gasleft() - 40000;
}
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
gasLimit,
destination,
value,
add(d, dataOffset),
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > 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
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract IZrxExchange {
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
}
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 hash of the order (see IZrxExchange.getOrderHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s).
}
function getOrderInfo(Order memory order)
public
view
returns (OrderInfo memory orderInfo);
function getOrdersInfo(Order[] memory orders)
public
view
returns (OrderInfo[] memory ordersInfo);
function fillOrder(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (FillResults memory fillResults);
function fillOrderNoThrow(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (FillResults memory fillResults);
}
contract IGST2 is IERC20 {
function freeUpTo(uint256 value) external returns (uint256 freed);
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
function balanceOf(address who) external view returns (uint256);
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
contract Shutdownable is Ownable {
bool public isShutdown;
event Shutdown();
modifier notShutdown {
require(!isShutdown, "Smart contract is shut down.");
_;
}
function shutdown() public onlyOwner {
isShutdown = true;
emit Shutdown();
}
}
contract IERC20NonView {
// Methods are not view to avoid throw on proxy tokens with delegatecall inside
function balanceOf(address user) public returns(uint256);
function allowance(address from, address to) public returns(uint256);
}
contract ZrxMarketOrder {
using SafeMath for uint256;
function marketSellOrdersProportion(
IERC20 tokenSell,
address tokenBuy,
address zrxExchange,
address zrxTokenProxy,
IZrxExchange.Order[] calldata orders,
bytes[] calldata signatures,
uint256 mul,
uint256 div
)
external
{
uint256 amount = tokenSell.balanceOf(msg.sender).mul(mul).div(div);
this.marketSellOrders(tokenBuy, zrxExchange, zrxTokenProxy, amount, orders, signatures);
}
function marketSellOrders(
address makerAsset,
address zrxExchange,
address zrxTokenProxy,
uint256 takerAssetFillAmount,
IZrxExchange.Order[] calldata orders,
bytes[] calldata signatures
)
external
returns (IZrxExchange.FillResults memory totalFillResults)
{
for (uint i = 0; i < orders.length; i++) {
// Stop execution if the entire amount of takerAsset has been sold
if (totalFillResults.takerAssetFilledAmount >= takerAssetFillAmount) {
break;
}
// Calculate the remaining amount of takerAsset to sell
uint256 remainingTakerAmount = takerAssetFillAmount.sub(totalFillResults.takerAssetFilledAmount);
IZrxExchange.OrderInfo memory orderInfo = IZrxExchange(zrxExchange).getOrderInfo(orders[i]);
uint256 orderRemainingTakerAmount = orders[i].takerAssetAmount.sub(orderInfo.orderTakerAssetFilledAmount);
// Check available balance and allowance and update orderRemainingTakerAmount
{
uint256 balance = IERC20NonView(makerAsset).balanceOf(orders[i].makerAddress);
uint256 allowance = IERC20NonView(makerAsset).allowance(orders[i].makerAddress, zrxTokenProxy);
uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
if (availableTakerAmount < orderRemainingTakerAmount) {
orderRemainingTakerAmount = availableTakerAmount;
}
}
uint256 takerAmount = (orderRemainingTakerAmount < remainingTakerAmount) ? orderRemainingTakerAmount : remainingTakerAmount;
IZrxExchange.FillResults memory fillResults = IZrxExchange(zrxExchange).fillOrderNoThrow(
orders[i],
takerAmount,
signatures[i]
);
_addFillResults(totalFillResults, fillResults);
}
return totalFillResults;
}
function _addFillResults(
IZrxExchange.FillResults memory totalFillResults,
IZrxExchange.FillResults memory singleFillResults
)
internal
pure
{
totalFillResults.makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount.add(singleFillResults.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = totalFillResults.takerAssetFilledAmount.add(singleFillResults.takerAssetFilledAmount);
totalFillResults.makerFeePaid = totalFillResults.makerFeePaid.add(singleFillResults.makerFeePaid);
totalFillResults.takerFeePaid = totalFillResults.takerFeePaid.add(singleFillResults.takerFeePaid);
}
function getOrdersInfoRespectingBalancesAndAllowances(
IERC20 token,
IZrxExchange zrx,
address zrxTokenProxy,
IZrxExchange.Order[] memory orders
)
public
view
returns (IZrxExchange.OrderInfo[] memory ordersInfo)
{
ordersInfo = zrx.getOrdersInfo(orders);
for (uint i = 0; i < ordersInfo.length; i++) {
uint256 balance = token.balanceOf(orders[i].makerAddress);
uint256 allowance = token.allowance(orders[i].makerAddress, zrxTokenProxy);
uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
for (uint j = 0; j < i; j++) {
if (orders[j].makerAddress == orders[i].makerAddress) {
uint256 orderTakerAssetRemainigAmount = orders[j].takerAssetAmount.sub(
ordersInfo[j].orderTakerAssetFilledAmount
);
if (availableTakerAmount > orderTakerAssetRemainigAmount) {
availableTakerAmount = availableTakerAmount.sub(orderTakerAssetRemainigAmount);
} else {
availableTakerAmount = 0;
break;
}
}
}
uint256 remainingTakerAmount = orders[i].takerAssetAmount.sub(
ordersInfo[i].orderTakerAssetFilledAmount
);
if (availableTakerAmount < remainingTakerAmount) {
ordersInfo[i].orderTakerAssetFilledAmount = orders[i].takerAssetAmount.sub(availableTakerAmount);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal {
universalTransfer(token, to, amount, false);
}
function universalTransfer(IERC20 token, address to, uint256 amount, bool mayFail) internal returns(bool) {
if (amount == 0) {
return true;
}
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
if (mayFail) {
return address(uint160(to)).send(amount);
} else {
address(uint160(to)).transfer(amount);
return true;
}
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (token != ZERO_ADDRESS && token != ETH_ADDRESS) {
token.safeApprove(to, amount);
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
require(from == msg.sender && msg.value >= amount, "msg.value is zero");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
}
contract TokenSpender {
using SafeERC20 for IERC20;
address public owner;
IGST2 public gasToken;
address public gasTokenOwner;
constructor(IGST2 _gasToken, address _gasTokenOwner) public {
owner = msg.sender;
gasToken = _gasToken;
gasTokenOwner = _gasTokenOwner;
}
function claimTokens(IERC20 token, address who, address dest, uint256 amount) external {
require(msg.sender == owner, "Access restricted");
token.safeTransferFrom(who, dest, amount);
}
function burnGasToken(uint gasSpent) external {
require(msg.sender == owner, "Access restricted");
uint256 tokens = (gasSpent + 14154) / 41130;
gasToken.freeUpTo(tokens);
}
function() external {
if (msg.sender == gasTokenOwner) {
gasToken.transfer(msg.sender, gasToken.balanceOf(address(this)));
}
}
}
contract OneInchExchange is Shutdownable, ZrxMarketOrder {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
using ExternalCall for address;
IERC20 constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
TokenSpender public spender;
uint fee; // 10000 => 100%, 1 => 0.01%
event History(
address indexed sender,
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount
);
event Swapped(
IERC20 indexed fromToken,
IERC20 indexed toToken,
address indexed referrer,
uint256 fromAmount,
uint256 toAmount,
uint256 referrerFee,
uint256 fee
);
constructor(address _owner, IGST2 _gasToken, uint _fee) public {
spender = new TokenSpender(
_gasToken,
_owner
);
_transferOwnership(_owner);
fee = _fee;
}
function() external payable notShutdown {
require(msg.sender != tx.origin);
}
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
uint256 guaranteedAmount,
address payable referrer,
address[] memory callAddresses,
bytes memory callDataConcat,
uint256[] memory starts,
uint256[] memory gasLimitsAndValues
)
public
payable
notShutdown
returns (uint256 returnAmount)
{
uint256 gasProvided = gasleft();
require(minReturnAmount > 0, "Min return should be bigger then 0.");
require(callAddresses.length > 0, "Call data should exists.");
if (fromToken != ETH_ADDRESS) {
spender.claimTokens(fromToken, msg.sender, address(this), fromTokenAmount);
}
for (uint i = 0; i < callAddresses.length; i++) {
require(callAddresses[i] != address(spender), "Access denied");
require(callAddresses[i].externalCall(
gasLimitsAndValues[i] & ((1 << 128) - 1),
callDataConcat,
starts[i],
starts[i + 1] - starts[i],
gasLimitsAndValues[i] >> 128
));
}
// Return back all unswapped
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
returnAmount = toToken.universalBalanceOf(address(this));
(uint256 toTokenAmount, uint256 referrerFee) = _handleFees(toToken, referrer, returnAmount, guaranteedAmount);
require(toTokenAmount >= minReturnAmount, "Return amount is not enough");
toToken.universalTransfer(msg.sender, toTokenAmount);
emit History(
msg.sender,
fromToken,
toToken,
fromTokenAmount,
toTokenAmount
);
emit Swapped(
fromToken,
toToken,
referrer,
fromTokenAmount,
toTokenAmount,
referrerFee,
returnAmount.sub(toTokenAmount)
);
spender.burnGasToken(gasProvided.sub(gasleft()));
}
function _handleFees(
IERC20 toToken,
address referrer,
uint256 returnAmount,
uint256 guaranteedAmount
)
internal
returns (
uint256 toTokenAmount,
uint256 referrerFee
)
{
if (returnAmount <= guaranteedAmount) {
return (returnAmount, 0);
}
uint256 feeAmount = returnAmount.sub(guaranteedAmount).mul(fee).div(10000);
if (referrer != address(0) && referrer != msg.sender && referrer != tx.origin) {
referrerFee = feeAmount.div(10);
if (toToken.universalTransfer(referrer, referrerFee, true)) {
returnAmount = returnAmount.sub(referrerFee);
feeAmount = feeAmount.sub(referrerFee);
} else {
referrerFee = 0;
}
}
if (toToken.universalTransfer(owner(), feeAmount, true)) {
returnAmount = returnAmount.sub(feeAmount);
}
return (returnAmount, referrerFee);
}
function infiniteApproveIfNeeded(IERC20 token, address to) external notShutdown {
if (token != ETH_ADDRESS) {
if ((token.allowance(address(this), to) >> 255) == 0) {
token.universalApprove(to, uint256(- 1));
}
}
}
function withdrawAllToken(IWETH token) external notShutdown {
uint256 amount = token.balanceOf(address(this));
token.withdraw(amount);
}
}File 2 of 14: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.18;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return this.balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/File 3 of 14: OneSplit
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IOneSplit.sol
pragma solidity ^0.5.0;
//
// [ msg.sender ]
// | |
// | |
// \_/
// +---------------+ ________________________________
// | OneSplitAudit | _______________________________ \
// +---------------+ \ \
// | | ______________ | | (staticcall)
// | | / ____________ \ | |
// | | (call) / / \ \ | |
// | | / / | | | |
// \_/ | | \_/ \_/
// +--------------+ | | +----------------------+
// | OneSplitWrap | | | | OneSplitViewWrap |
// +--------------+ | | +----------------------+
// | | | | | |
// | | (delegatecall) | | (staticcall) | | (staticcall)
// \_/ | | \_/
// +--------------+ | | +------------------+
// | OneSplit | | | | OneSplitView |
// +--------------+ | | +------------------+
// | | / /
// \ \________________/ /
// \__________________/
//
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
)
public
payable
returns(uint256 returnAmount);
}
contract IOneSplitMulti is IOneSplit {
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
)
public
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/interface/IUniswapExchange.sol
pragma solidity ^0.5.0;
interface IUniswapExchange {
function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought);
function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
external
payable
returns (uint256 tokensBought);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
external
returns (uint256 ethBought);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddr
) external returns (uint256 tokensBought);
}
// File: contracts/interface/IUniswapFactory.sol
pragma solidity ^0.5.0;
interface IUniswapFactory {
function getExchange(IERC20 token) external view returns (IUniswapExchange exchange);
}
// File: contracts/interface/IKyberNetworkContract.sol
pragma solidity ^0.5.0;
interface IKyberNetworkContract {
function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless)
external
view
returns (address reserve, uint256 rate);
}
// File: contracts/interface/IKyberNetworkProxy.sol
pragma solidity ^0.5.0;
interface IKyberNetworkProxy {
function getExpectedRateAfterFee(
IERC20 src,
IERC20 dest,
uint256 srcQty,
uint256 platformFeeBps,
bytes calldata hint
) external view returns (uint256 expectedRate);
function tradeWithHintAndFee(
IERC20 src,
uint256 srcAmount,
IERC20 dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable platformWallet,
uint256 platformFeeBps,
bytes calldata hint
) external payable returns (uint256 destAmount);
function kyberNetworkContract() external view returns (IKyberNetworkContract);
// TODO: Limit usage by tx.gasPrice
// function maxGasPrice() external view returns (uint256);
// TODO: Limit usage by user cap
// function getUserCapInWei(address user) external view returns (uint256);
// function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256);
}
// File: contracts/interface/IKyberStorage.sol
pragma solidity ^0.5.0;
interface IKyberStorage {
function getReserveIdsPerTokenSrc(
IERC20 token
) external view returns (bytes32[] memory);
}
// File: contracts/interface/IKyberHintHandler.sol
pragma solidity ^0.5.0;
interface IKyberHintHandler {
enum TradeType {
BestOfAll,
MaskIn,
MaskOut,
Split
}
function buildTokenToEthHint(
IERC20 tokenSrc,
TradeType tokenToEthType,
bytes32[] calldata tokenToEthReserveIds,
uint256[] calldata tokenToEthSplits
) external view returns (bytes memory hint);
function buildEthToTokenHint(
IERC20 tokenDest,
TradeType ethToTokenType,
bytes32[] calldata ethToTokenReserveIds,
uint256[] calldata ethToTokenSplits
) external view returns (bytes memory hint);
}
// File: contracts/interface/IBancorNetwork.sol
pragma solidity ^0.5.0;
interface IBancorNetwork {
function getReturnByPath(address[] calldata path, uint256 amount)
external
view
returns (uint256 returnAmount, uint256 conversionFee);
function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn)
external
returns (uint256);
function convert(address[] calldata path, uint256 amount, uint256 minReturn)
external
payable
returns (uint256);
}
// File: contracts/interface/IBancorContractRegistry.sol
pragma solidity ^0.5.0;
contract IBancorContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
// File: contracts/interface/IBancorNetworkPathFinder.sol
pragma solidity ^0.5.0;
interface IBancorNetworkPathFinder {
function generatePath(IERC20 sourceToken, IERC20 targetToken)
external
view
returns (address[] memory);
}
// File: contracts/interface/IBancorConverterRegistry.sol
pragma solidity ^0.5.0;
interface IBancorConverterRegistry {
function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken)
external view returns(uint256);
function getConvertibleTokenSmartTokens(IERC20 convertibleToken)
external view returns(address[] memory);
function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index)
external view returns(address);
function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value)
external view returns(bool);
}
// File: contracts/interface/IBancorEtherToken.sol
pragma solidity ^0.5.0;
contract IBancorEtherToken is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/IBancorFinder.sol
pragma solidity ^0.5.0;
interface IBancorFinder {
function buildBancorPath(
IERC20 fromToken,
IERC20 destToken
)
external
view
returns(address[] memory path);
}
// File: contracts/interface/IOasisExchange.sol
pragma solidity ^0.5.0;
interface IOasisExchange {
function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt)
external
view
returns (uint256 fillAmt);
function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount)
external
returns (uint256 fillAmt);
}
// File: contracts/interface/IWETH.sol
pragma solidity ^0.5.0;
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/ICurve.sol
pragma solidity ^0.5.0;
interface ICurve {
// solium-disable-next-line mixedcase
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function get_dy(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external;
// solium-disable-next-line mixedcase
function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external;
}
contract ICurveRegistry {
function get_pool_info(address pool)
external
view
returns(
uint256[8] memory balances,
uint256[8] memory underlying_balances,
uint256[8] memory decimals,
uint256[8] memory underlying_decimals,
address lp_token,
uint256 A,
uint256 fee
);
}
contract ICurveCalculator {
function get_dy(
int128 nCoins,
uint256[8] calldata balances,
uint256 amp,
uint256 fee,
uint256[8] calldata rates,
uint256[8] calldata precisions,
bool underlying,
int128 i,
int128 j,
uint256[100] calldata dx
) external view returns(uint256[100] memory dy);
}
// File: contracts/interface/IChai.sol
pragma solidity ^0.5.0;
interface IPot {
function dsr() external view returns (uint256);
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
contract IChai is IERC20 {
function POT() public view returns (IPot);
function join(address dst, uint256 wad) external;
function exit(address src, uint256 wad) external;
}
library ChaiHelper {
IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
uint256 private constant RAY = 10**27;
function _mul(uint256 x, uint256 y) private pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, y) / RAY;
}
function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, RAY) / y;
}
function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) {
// solium-disable-next-line security/no-inline-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
function potDrip() private view returns (uint256) {
return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi());
}
function chaiPrice(IChai chai) internal view returns(uint256) {
return chaiToDai(chai, 1e18);
}
function daiToChai(
IChai /*chai*/,
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rdiv(amount, chi);
}
function chaiToDai(
IChai /*chai*/,
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rmul(chi, amount);
}
}
// File: contracts/interface/ICompound.sol
pragma solidity ^0.5.0;
contract ICompound {
function markets(address cToken)
external
view
returns (bool isListed, uint256 collateralFactorMantissa);
}
contract ICompoundToken is IERC20 {
function underlying() external view returns (address);
function exchangeRateStored() external view returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
}
contract ICompoundEther is IERC20 {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
}
// File: contracts/interface/ICompoundRegistry.sol
pragma solidity ^0.5.0;
contract ICompoundRegistry {
function tokenByCToken(ICompoundToken cToken) external view returns(IERC20);
function cTokenByToken(IERC20 token) external view returns(ICompoundToken);
}
// File: contracts/interface/IAaveToken.sol
pragma solidity ^0.5.0;
contract IAaveToken is IERC20 {
function underlyingAssetAddress() external view returns (IERC20);
function redeem(uint256 amount) external;
}
interface IAaveLendingPool {
function core() external view returns (address);
function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
}
// File: contracts/interface/IAaveRegistry.sol
pragma solidity ^0.5.0;
contract IAaveRegistry {
function tokenByAToken(IAaveToken aToken) external view returns(IERC20);
function aTokenByToken(IERC20 token) external view returns(IAaveToken);
}
// File: contracts/interface/IMooniswap.sol
pragma solidity ^0.5.0;
interface IMooniswapRegistry {
function pools(IERC20 token1, IERC20 token2) external view returns(IMooniswap);
function isPool(address addr) external view returns(bool);
}
interface IMooniswap {
function fee() external view returns (uint256);
function tokens(uint256 i) external view returns (IERC20);
function deposit(uint256[] calldata amounts, uint256[] calldata minAmounts) external payable returns(uint256 fairSupply);
function withdraw(uint256 amount, uint256[] calldata minReturns) external;
function getBalanceForAddition(IERC20 token) external view returns(uint256);
function getBalanceForRemoval(IERC20 token) external view returns(uint256);
function getReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
)
external
view
returns(uint256 returnAmount);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
address referral
)
external
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
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 Returns the average of two numbers. The result is rounded towards
* zero.
*/
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: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/UniversalERC20.sol
pragma solidity ^0.5.0;
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount == 0) {
token.safeApprove(to, 0);
return;
}
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
function eq(IERC20 a, IERC20 b) internal pure returns(bool) {
return a == b || (isETH(a) && isETH(b));
}
function notExist(IERC20 token) internal pure returns(bool) {
return (address(token) == address(-1));
}
}
// File: contracts/interface/IUniswapV2Exchange.sol
pragma solidity ^0.5.0;
interface IUniswapV2Exchange {
function getReserves() external view returns(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
}
library UniswapV2ExchangeLib {
using Math for uint256;
using SafeMath for uint256;
using UniversalERC20 for IERC20;
function getReturn(
IUniswapV2Exchange exchange,
IERC20 fromToken,
IERC20 destToken,
uint amountIn
) internal view returns (uint256 result, bool needSync, bool needSkim) {
uint256 reserveIn = fromToken.universalBalanceOf(address(exchange));
uint256 reserveOut = destToken.universalBalanceOf(address(exchange));
(uint112 reserve0, uint112 reserve1,) = exchange.getReserves();
if (fromToken > destToken) {
(reserve0, reserve1) = (reserve1, reserve0);
}
needSync = (reserveIn < reserve0 || reserveOut < reserve1);
needSkim = !needSync && (reserveIn > reserve0 || reserveOut > reserve1);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(Math.min(reserveOut, reserve1));
uint256 denominator = Math.min(reserveIn, reserve0).mul(1000).add(amountInWithFee);
result = (denominator == 0) ? 0 : numerator.div(denominator);
}
}
// File: contracts/interface/IUniswapV2Factory.sol
pragma solidity ^0.5.0;
interface IUniswapV2Factory {
function getPair(IERC20 tokenA, IERC20 tokenB) external view returns (IUniswapV2Exchange pair);
}
// File: contracts/interface/IDForceSwap.sol
pragma solidity ^0.5.0;
interface IDForceSwap {
function getAmountByInput(IERC20 input, IERC20 output, uint256 amount) external view returns(uint256);
function swap(IERC20 input, IERC20 output, uint256 amount) external;
}
// File: contracts/interface/IShell.sol
pragma solidity ^0.5.0;
interface IShell {
function viewOriginTrade(
address origin,
address target,
uint256 originAmount
) external view returns (uint256);
function swapByOrigin(
address origin,
address target,
uint256 originAmount,
uint256 minTargetAmount,
uint256 deadline
) external returns (uint256);
}
// File: contracts/interface/IMStable.sol
pragma solidity ^0.5.0;
contract IMStable is IERC20 {
function getSwapOutput(
IERC20 _input,
IERC20 _output,
uint256 _quantity
)
external
view
returns (bool, string memory, uint256 output);
function swap(
IERC20 _input,
IERC20 _output,
uint256 _quantity,
address _recipient
)
external
returns (uint256 output);
function redeem(
IERC20 _basset,
uint256 _bassetQuantity
)
external
returns (uint256 massetRedeemed);
}
interface IMassetValidationHelper {
/**
* @dev Returns a valid bAsset to redeem
* @param _mAsset Masset addr
* @return valid bool
* @return string message
* @return address of bAsset to redeem
*/
function suggestRedeemAsset(
IERC20 _mAsset
)
external
view
returns (
bool valid,
string memory err,
address token
);
/**
* @dev Returns a valid bAsset with which to mint
* @param _mAsset Masset addr
* @return valid bool
* @return string message
* @return address of bAsset to mint
*/
function suggestMintAsset(
IERC20 _mAsset
)
external
view
returns (
bool valid,
string memory err,
address token
);
/**
* @dev Determines if a given Redemption is valid
* @param _mAsset Address of the given mAsset (e.g. mUSD)
* @param _mAssetQuantity Amount of mAsset to redeem (in mUSD units)
* @param _outputBasset Desired output bAsset
* @return valid
* @return validity reason
* @return output in bAsset units
* @return bAssetQuantityArg - required input argument to the 'redeem' call
*/
function getRedeemValidity(
IERC20 _mAsset,
uint256 _mAssetQuantity,
IERC20 _outputBasset
)
external
view
returns (
bool valid,
string memory,
uint256 output,
uint256 bassetQuantityArg
);
}
// File: contracts/interface/IBalancerPool.sol
pragma solidity ^0.5.0;
interface IBalancerPool {
function getSwapFee()
external view returns (uint256 balance);
function getDenormalizedWeight(IERC20 token)
external view returns (uint256 balance);
function getBalance(IERC20 token)
external view returns (uint256 balance);
function swapExactAmountIn(
IERC20 tokenIn,
uint256 tokenAmountIn,
IERC20 tokenOut,
uint256 minAmountOut,
uint256 maxPrice
)
external
returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
}
// 0xA961672E8Db773be387e775bc4937C678F3ddF9a
interface IBalancerHelper {
function getReturns(
IBalancerPool pool,
IERC20 fromToken,
IERC20 destToken,
uint256[] calldata amounts
)
external
view
returns(uint256[] memory rets);
}
// File: contracts/interface/IBalancerRegistry.sol
pragma solidity ^0.5.0;
interface IBalancerRegistry {
event PoolAdded(
address indexed pool
);
event PoolTokenPairAdded(
address indexed pool,
address indexed fromToken,
address indexed destToken
);
event IndicesUpdated(
address indexed fromToken,
address indexed destToken,
bytes32 oldIndices,
bytes32 newIndices
);
// Get info about pool pair for 1 SLOAD
function getPairInfo(address pool, address fromToken, address destToken)
external view returns(uint256 weight1, uint256 weight2, uint256 swapFee);
// Pools
function checkAddedPools(address pool)
external view returns(bool);
function getAddedPoolsLength()
external view returns(uint256);
function getAddedPools()
external view returns(address[] memory);
function getAddedPoolsWithLimit(uint256 offset, uint256 limit)
external view returns(address[] memory result);
// Tokens
function getAllTokensLength()
external view returns(uint256);
function getAllTokens()
external view returns(address[] memory);
function getAllTokensWithLimit(uint256 offset, uint256 limit)
external view returns(address[] memory result);
// Pairs
function getPoolsLength(address fromToken, address destToken)
external view returns(uint256);
function getPools(address fromToken, address destToken)
external view returns(address[] memory);
function getPoolsWithLimit(address fromToken, address destToken, uint256 offset, uint256 limit)
external view returns(address[] memory result);
function getBestPools(address fromToken, address destToken)
external view returns(address[] memory pools);
function getBestPoolsWithLimit(address fromToken, address destToken, uint256 limit)
external view returns(address[] memory pools);
// Get swap rates
function getPoolReturn(address pool, address fromToken, address destToken, uint256 amount)
external view returns(uint256);
function getPoolReturns(address pool, address fromToken, address destToken, uint256[] calldata amounts)
external view returns(uint256[] memory result);
// Add and update registry
function addPool(address pool) external returns(uint256 listed);
function addPools(address[] calldata pools) external returns(uint256[] memory listed);
function updatedIndices(address[] calldata tokens, uint256 lengthLimit) external;
}
// File: contracts/BalancerLib.sol
pragma solidity ^0.5.0;
library BalancerLib {
uint public constant BONE = 10**18;
uint public constant MIN_BOUND_TOKENS = 2;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant MIN_FEE = BONE / 10**6;
uint public constant MAX_FEE = BONE / 10;
uint public constant EXIT_FEE = 0;
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**12;
uint public constant INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
function btoi(uint a)
internal pure
returns (uint)
{
return a / BONE;
}
function bfloor(uint a)
internal pure
returns (uint)
{
return btoi(a) * BONE;
}
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint a, uint n)
internal pure
returns (uint)
{
uint z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint base, uint exp)
internal pure
returns (uint)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint whole = bfloor(exp);
uint remain = bsub(exp, whole);
uint wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
// term 0:
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
)
internal pure
returns (uint spotPrice)
{
uint numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint ratio = bdiv(numer, denom);
uint scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
)
internal pure
returns (uint tokenAmountOut)
{
uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
if (y == 0) {
return 0;
}
uint foo = bpow(y, weightRatio);
uint bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
)
internal pure
returns (uint tokenAmountIn)
{
uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint diff = bsub(tokenBalanceOut, tokenAmountOut);
uint y = bdiv(tokenBalanceOut, diff);
if (y == 0) {
return 0;
}
uint foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
)
internal pure
returns (uint poolAmountOut)
{
// Charge the trading fee for the proportion of tokenAi
/// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint poolRatio = bpow(tokenInRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
internal pure
returns (uint tokenAmountIn)
{
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint newPoolSupply = badd(poolSupply, poolAmountOut);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint boo = bdiv(BONE, normalizedWeight);
uint tokenInRatio = bpow(poolRatio, boo);
uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
)
internal pure
returns (uint tokenAmountOut)
{
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE));
uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
)
internal pure
returns (uint poolAmountIn)
{
// charge swap fee on the output token side
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint zoo = bsub(BONE, normalizedWeight);
uint zar = bmul(zoo, swapFee);
uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));
return poolAmountIn;
}
}
// File: contracts/OneSplitBase.sol
pragma solidity ^0.5.0;
contract IOneSplitView is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
}
library DisableFlags {
function check(uint256 flags, uint256 flag) internal pure returns(bool) {
return (flags & flag) != 0;
}
}
contract OneSplitRoot is IOneSplitView {
using SafeMath for uint256;
using DisableFlags for uint256;
using UniversalERC20 for IERC20;
using UniversalERC20 for IWETH;
using UniswapV2ExchangeLib for IUniswapV2Exchange;
using ChaiHelper for IChai;
uint256 constant internal DEXES_COUNT = 34;
IERC20 constant internal ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 constant internal ZERO_ADDRESS = IERC20(0);
IBancorEtherToken constant internal bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IChai constant internal chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
IERC20 constant internal dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 constant internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 constant internal usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 constant internal tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
IERC20 constant internal busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
IERC20 constant internal susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
IERC20 constant internal pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1);
IERC20 constant internal renbtc = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D);
IERC20 constant internal wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IERC20 constant internal tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847);
IERC20 constant internal hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380);
IERC20 constant internal sbtc = IERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6);
IKyberNetworkProxy constant internal kyberNetworkProxy = IKyberNetworkProxy(0x9AAb3f75489902f3a48495025729a0AF77d4b11e);
IKyberStorage constant internal kyberStorage = IKyberStorage(0xC8fb12402cB16970F3C5F4b48Ff68Eb9D1289301);
IKyberHintHandler constant internal kyberHintHandler = IKyberHintHandler(0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C);
IUniswapFactory constant internal uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
IBancorContractRegistry constant internal bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4);
IBancorNetworkPathFinder constant internal bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
//IBancorConverterRegistry constant internal bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518);
IBancorFinder constant internal bancorFinder = IBancorFinder(0x2B344e14dc2641D11D338C053C908c7A7D4c30B9);
IOasisExchange constant internal oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D);
ICurve constant internal curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56);
ICurve constant internal curveUSDT = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C);
ICurve constant internal curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
ICurve constant internal curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27);
ICurve constant internal curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD);
ICurve constant internal curvePAX = ICurve(0x06364f10B501e868329afBc005b3492902d6C763);
ICurve constant internal curveRenBTC = ICurve(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
ICurve constant internal curveTBTC = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E);
ICurve constant internal curveSBTC = ICurve(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714);
IShell constant internal shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D);
IAaveLendingPool constant internal aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
ICompound constant internal compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ICompoundEther constant internal cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
IMooniswapRegistry constant internal mooniswapRegistry = IMooniswapRegistry(0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303);
IUniswapV2Factory constant internal uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
IDForceSwap constant internal dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2);
IMStable constant internal musd = IMStable(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
IMassetValidationHelper constant internal musd_helper = IMassetValidationHelper(0xaBcC93c3be238884cc3309C19Afd128fAfC16911);
IBalancerRegistry constant internal balancerRegistry = IBalancerRegistry(0x65e67cbc342712DF67494ACEfc06fe951EE93982);
ICurveCalculator constant internal curveCalculator = ICurveCalculator(0xc1DB00a8E5Ef7bfa476395cdbcc98235477cDE4E);
ICurveRegistry constant internal curveRegistry = ICurveRegistry(0x7002B727Ef8F5571Cb5F9D70D13DBEEb4dFAe9d1);
ICompoundRegistry constant internal compoundRegistry = ICompoundRegistry(0xF451Dbd7Ba14BFa7B1B78A766D3Ed438F79EE1D1);
IAaveRegistry constant internal aaveRegistry = IAaveRegistry(0xEd8b133B7B88366E01Bb9E38305Ab11c26521494);
IBalancerHelper constant internal balancerHelper = IBalancerHelper(0xA961672E8Db773be387e775bc4937C678F3ddF9a);
int256 internal constant VERY_NEGATIVE_VALUE = -1e72;
function _findBestDistribution(
uint256 s, // parts
int256[][] memory amounts // exchangesReturns
)
internal
pure
returns(
int256 returnAmount,
uint256[] memory distribution
)
{
uint256 n = amounts.length;
int256[][] memory answer = new int256[][](n); // int[n][s+1]
uint256[][] memory parent = new uint256[][](n); // int[n][s+1]
for (uint i = 0; i < n; i++) {
answer[i] = new int256[](s + 1);
parent[i] = new uint256[](s + 1);
}
for (uint j = 0; j <= s; j++) {
answer[0][j] = amounts[0][j];
for (uint i = 1; i < n; i++) {
answer[i][j] = -1e72;
}
parent[0][j] = 0;
}
for (uint i = 1; i < n; i++) {
for (uint j = 0; j <= s; j++) {
answer[i][j] = answer[i - 1][j];
parent[i][j] = j;
for (uint k = 1; k <= j; k++) {
if (answer[i - 1][j - k] + amounts[i][k] > answer[i][j]) {
answer[i][j] = answer[i - 1][j - k] + amounts[i][k];
parent[i][j] = j - k;
}
}
}
}
distribution = new uint256[](DEXES_COUNT);
uint256 partsLeft = s;
for (uint curExchange = n - 1; partsLeft > 0; curExchange--) {
distribution[curExchange] = partsLeft - parent[curExchange][partsLeft];
partsLeft = parent[curExchange][partsLeft];
}
returnAmount = (answer[n - 1][s] == VERY_NEGATIVE_VALUE) ? 0 : answer[n - 1][s];
}
function _kyberReserveIdByTokens(
IERC20 fromToken,
IERC20 destToken
) internal view returns(bytes32) {
if (!fromToken.isETH() && !destToken.isETH()) {
return 0;
}
bytes32[] memory reserveIds = kyberStorage.getReserveIdsPerTokenSrc(
fromToken.isETH() ? destToken : fromToken
);
for (uint i = 0; i < reserveIds.length; i++) {
if ((uint256(reserveIds[i]) >> 248) != 0xBB && // Bridge
reserveIds[i] != 0xff4b796265722046707200000000000000000000000000000000000000000000 && // Reserve 1
reserveIds[i] != 0xffabcd0000000000000000000000000000000000000000000000000000000000 && // Reserve 2
reserveIds[i] != 0xff4f6e65426974205175616e7400000000000000000000000000000000000000) // Reserve 3
{
return reserveIds[i];
}
}
return 0;
}
function _scaleDestTokenEthPriceTimesGasPrice(
IERC20 fromToken,
IERC20 destToken,
uint256 destTokenEthPriceTimesGasPrice
) internal view returns(uint256) {
if (fromToken == destToken) {
return destTokenEthPriceTimesGasPrice;
}
uint256 mul = _cheapGetPrice(ETH_ADDRESS, destToken, 0.01 ether);
uint256 div = _cheapGetPrice(ETH_ADDRESS, fromToken, 0.01 ether);
if (div > 0) {
return destTokenEthPriceTimesGasPrice.mul(mul).div(div);
}
return 0;
}
function _cheapGetPrice(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal view returns(uint256 returnAmount) {
(returnAmount,,) = this.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
1,
FLAG_DISABLE_SPLIT_RECALCULATION |
FLAG_DISABLE_ALL_SPLIT_SOURCES |
FLAG_DISABLE_UNISWAP_V2_ALL |
FLAG_DISABLE_UNISWAP,
0
);
}
function _linearInterpolation(
uint256 value,
uint256 parts
) internal pure returns(uint256[] memory rets) {
rets = new uint256[](parts);
for (uint i = 0; i < parts; i++) {
rets[i] = value.mul(i + 1).div(parts);
}
}
function _tokensEqual(IERC20 tokenA, IERC20 tokenB) internal pure returns(bool) {
return ((tokenA.isETH() && tokenB.isETH()) || tokenA == tokenB);
}
}
contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = this.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _getExpectedReturnRespectingGasFloor(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnRespectingGasFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
}
contract OneSplitView is IOneSplitView, OneSplitRoot {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
if (fromToken == destToken) {
return (amount, 0, distribution);
}
function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory reserves = _getAllReserves(flags);
int256[][] memory matrix = new int256[][](DEXES_COUNT);
uint256[DEXES_COUNT] memory gases;
bool atLeastOnePositive = false;
for (uint i = 0; i < DEXES_COUNT; i++) {
uint256[] memory rets;
(rets, gases[i]) = reserves[i](fromToken, destToken, amount, parts, flags);
// Prepend zero and sub gas
int256 gas = int256(gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18));
matrix[i] = new int256[](parts + 1);
for (uint j = 0; j < rets.length; j++) {
matrix[i][j + 1] = int256(rets[j]) - gas;
atLeastOnePositive = atLeastOnePositive || (matrix[i][j + 1] > 0);
}
}
if (!atLeastOnePositive) {
for (uint i = 0; i < DEXES_COUNT; i++) {
for (uint j = 1; j < parts + 1; j++) {
if (matrix[i][j] == 0) {
matrix[i][j] = VERY_NEGATIVE_VALUE;
}
}
}
}
(, distribution) = _findBestDistribution(parts, matrix);
(returnAmount, estimateGasAmount) = _getReturnAndGasByDistribution(
Args({
fromToken: fromToken,
destToken: destToken,
amount: amount,
parts: parts,
flags: flags,
destTokenEthPriceTimesGasPrice: destTokenEthPriceTimesGasPrice,
distribution: distribution,
matrix: matrix,
gases: gases,
reserves: reserves
})
);
return (returnAmount, estimateGasAmount, distribution);
}
struct Args {
IERC20 fromToken;
IERC20 destToken;
uint256 amount;
uint256 parts;
uint256 flags;
uint256 destTokenEthPriceTimesGasPrice;
uint256[] distribution;
int256[][] matrix;
uint256[DEXES_COUNT] gases;
function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] reserves;
}
function _getReturnAndGasByDistribution(
Args memory args
) internal view returns(uint256 returnAmount, uint256 estimateGasAmount) {
bool[DEXES_COUNT] memory exact = [
true, // "Uniswap",
false, // "Kyber",
false, // "Bancor",
false, // "Oasis",
true, // "Curve Compound",
true, // "Curve USDT",
true, // "Curve Y",
true, // "Curve Binance",
true, // "Curve Synthetix",
true, // "Uniswap Compound",
true, // "Uniswap CHAI",
true, // "Uniswap Aave",
true, // "Mooniswap 1",
true, // "Uniswap V2",
true, // "Uniswap V2 (ETH)",
true, // "Uniswap V2 (DAI)",
true, // "Uniswap V2 (USDC)",
true, // "Curve Pax",
true, // "Curve RenBTC",
true, // "Curve tBTC",
true, // "Dforce XSwap",
false, // "Shell",
true, // "mStable",
true, // "Curve sBTC"
true, // "Balancer 1"
true, // "Balancer 2"
true, // "Balancer 3"
true, // "Kyber 1"
true, // "Kyber 2"
true, // "Kyber 3"
true, // "Kyber 4"
true, // "Mooniswap 2"
true, // "Mooniswap 3"
true // "Mooniswap 4"
];
for (uint i = 0; i < DEXES_COUNT; i++) {
if (args.distribution[i] > 0) {
if (args.distribution[i] == args.parts || exact[i] || args.flags.check(FLAG_DISABLE_SPLIT_RECALCULATION)) {
estimateGasAmount = estimateGasAmount.add(args.gases[i]);
int256 value = args.matrix[i][args.distribution[i]];
returnAmount = returnAmount.add(uint256(
(value == VERY_NEGATIVE_VALUE ? 0 : value) +
int256(args.gases[i].mul(args.destTokenEthPriceTimesGasPrice).div(1e18))
));
}
else {
(uint256[] memory rets, uint256 gas) = args.reserves[i](args.fromToken, args.destToken, args.amount.mul(args.distribution[i]).div(args.parts), 1, args.flags);
estimateGasAmount = estimateGasAmount.add(gas);
returnAmount = returnAmount.add(rets[0]);
}
}
}
}
function _getAllReserves(uint256 flags)
internal
pure
returns(function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory)
{
bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES);
return [
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP) ? _calculateNoReturn : calculateUniswap,
_calculateNoReturn, // invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyber,
invert != flags.check(FLAG_DISABLE_BANCOR) ? _calculateNoReturn : calculateBancor,
invert != flags.check(FLAG_DISABLE_OASIS) ? _calculateNoReturn : calculateOasis,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_COMPOUND) ? _calculateNoReturn : calculateCurveCompound,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_USDT) ? _calculateNoReturn : calculateCurveUSDT,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_Y) ? _calculateNoReturn : calculateCurveY,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_BINANCE) ? _calculateNoReturn : calculateCurveBinance,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SYNTHETIX) ? _calculateNoReturn : calculateCurveSynthetix,
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_COMPOUND) ? _calculateNoReturn : calculateUniswapCompound,
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_CHAI) ? _calculateNoReturn : calculateUniswapChai,
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_AAVE) ? _calculateNoReturn : calculateUniswapAave,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP) ? _calculateNoReturn : calculateMooniswap,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2) ? _calculateNoReturn : calculateUniswapV2,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_ETH) ? _calculateNoReturn : calculateUniswapV2ETH,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_DAI) ? _calculateNoReturn : calculateUniswapV2DAI,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_PAX) ? _calculateNoReturn : calculateCurvePAX,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_RENBTC) ? _calculateNoReturn : calculateCurveRenBTC,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_TBTC) ? _calculateNoReturn : calculateCurveTBTC,
invert != flags.check(FLAG_DISABLE_DFORCE_SWAP) ? _calculateNoReturn : calculateDforceSwap,
invert != flags.check(FLAG_DISABLE_SHELL) ? _calculateNoReturn : calculateShell,
invert != flags.check(FLAG_DISABLE_MSTABLE_MUSD) ? _calculateNoReturn : calculateMStableMUSD,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SBTC) ? _calculateNoReturn : calculateCurveSBTC,
invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_1) ? _calculateNoReturn : calculateBalancer1,
invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_2) ? _calculateNoReturn : calculateBalancer2,
invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_3) ? _calculateNoReturn : calculateBalancer3,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_1) ? _calculateNoReturn : calculateKyber1,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_2) ? _calculateNoReturn : calculateKyber2,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_3) ? _calculateNoReturn : calculateKyber3,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_4) ? _calculateNoReturn : calculateKyber4,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP_ETH) ? _calculateNoReturn : calculateMooniswapOverETH,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP_DAI) ? _calculateNoReturn : calculateMooniswapOverDAI,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP_USDC) ? _calculateNoReturn : calculateMooniswapOverUSDC
];
}
function _calculateNoGas(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 /*parts*/,
uint256 /*destTokenEthPriceTimesGasPrice*/,
uint256 /*flags*/,
uint256 /*destTokenEthPrice*/
) internal view returns(uint256[] memory /*rets*/, uint256 /*gas*/) {
this;
}
// View Helpers
struct Balances {
uint256 src;
uint256 dst;
}
function _calculateBalancer(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 poolIndex
) internal view returns(uint256[] memory rets, uint256 gas) {
address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
address(fromToken.isETH() ? weth : fromToken),
address(destToken.isETH() ? weth : destToken),
poolIndex + 1
);
if (poolIndex >= pools.length) {
return (new uint256[](parts), 0);
}
rets = balancerHelper.getReturns(
IBalancerPool(pools[poolIndex]),
fromToken.isETH() ? weth : fromToken,
destToken.isETH() ? weth : destToken,
_linearInterpolation(amount, parts)
);
gas = 75_000 + (fromToken.isETH() || destToken.isETH() ? 0 : 65_000);
}
function calculateBalancer1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateBalancer(
fromToken,
destToken,
amount,
parts,
0
);
}
function calculateBalancer2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateBalancer(
fromToken,
destToken,
amount,
parts,
1
);
}
function calculateBalancer3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateBalancer(
fromToken,
destToken,
amount,
parts,
2
);
}
function calculateMStableMUSD(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](parts);
if ((fromToken != usdc && fromToken != dai && fromToken != usdt && fromToken != tusd) ||
(destToken != usdc && destToken != dai && destToken != usdt && destToken != tusd))
{
return (rets, 0);
}
for (uint i = 1; i <= parts; i *= 2) {
(bool success, bytes memory data) = address(musd).staticcall(abi.encodeWithSelector(
musd.getSwapOutput.selector,
fromToken,
destToken,
amount.mul(parts.div(i)).div(parts)
));
if (success && data.length > 0) {
(,, uint256 maxRet) = abi.decode(data, (bool,string,uint256));
if (maxRet > 0) {
for (uint j = 0; j < parts.div(i); j++) {
rets[j] = maxRet.mul(j + 1).div(parts.div(i));
}
break;
}
}
}
return (
rets,
700_000
);
}
function _getCurvePoolInfo(
ICurve curve,
bool haveUnderlying
) internal view returns(
uint256[8] memory balances,
uint256[8] memory precisions,
uint256[8] memory rates,
uint256 amp,
uint256 fee
) {
uint256[8] memory underlying_balances;
uint256[8] memory decimals;
uint256[8] memory underlying_decimals;
(
balances,
underlying_balances,
decimals,
underlying_decimals,
/*address lp_token*/,
amp,
fee
) = curveRegistry.get_pool_info(address(curve));
for (uint k = 0; k < 8 && balances[k] > 0; k++) {
precisions[k] = 10 ** (18 - (haveUnderlying ? underlying_decimals : decimals)[k]);
if (haveUnderlying) {
rates[k] = underlying_balances[k].mul(1e18).div(balances[k]);
} else {
rates[k] = 1e18;
}
}
}
function _calculateCurveSelector(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
ICurve curve,
bool haveUnderlying,
IERC20[] memory tokens
) internal view returns(uint256[] memory rets) {
rets = new uint256[](parts);
int128 i = 0;
int128 j = 0;
for (uint t = 0; t < tokens.length; t++) {
if (fromToken == tokens[t]) {
i = int128(t + 1);
}
if (destToken == tokens[t]) {
j = int128(t + 1);
}
}
if (i == 0 || j == 0) {
return rets;
}
bytes memory data = abi.encodePacked(
uint256(haveUnderlying ? 1 : 0),
uint256(i - 1),
uint256(j - 1),
_linearInterpolation100(amount, parts)
);
(
uint256[8] memory balances,
uint256[8] memory precisions,
uint256[8] memory rates,
uint256 amp,
uint256 fee
) = _getCurvePoolInfo(curve, haveUnderlying);
bool success;
(success, data) = address(curveCalculator).staticcall(
abi.encodePacked(
abi.encodeWithSelector(
curveCalculator.get_dy.selector,
tokens.length,
balances,
amp,
fee,
rates,
precisions
),
data
)
);
if (!success || data.length == 0) {
return rets;
}
uint256[100] memory dy = abi.decode(data, (uint256[100]));
for (uint t = 0; t < parts; t++) {
rets[t] = dy[t];
}
}
function _linearInterpolation100(
uint256 value,
uint256 parts
) internal pure returns(uint256[100] memory rets) {
for (uint i = 0; i < parts; i++) {
rets[i] = value.mul(i + 1).div(parts);
}
}
function calculateCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = dai;
tokens[1] = usdc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveCompound,
true,
tokens
), 720_000);
}
function calculateCurveUSDT(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveUSDT,
true,
tokens
), 720_000);
}
function calculateCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = tusd;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveY,
true,
tokens
), 1_400_000);
}
function calculateCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = busd;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveBinance,
true,
tokens
), 1_400_000);
}
function calculateCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = susd;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveSynthetix,
true,
tokens
), 200_000);
}
function calculateCurvePAX(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = pax;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curvePAX,
true,
tokens
), 1_000_000);
}
function calculateCurveRenBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = renbtc;
tokens[1] = wbtc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveRenBTC,
false,
tokens
), 130_000);
}
function calculateCurveTBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = tbtc;
tokens[1] = wbtc;
tokens[2] = hbtc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveTBTC,
false,
tokens
), 145_000);
}
function calculateCurveSBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = renbtc;
tokens[1] = wbtc;
tokens[2] = sbtc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveSBTC,
false,
tokens
), 150_000);
}
function calculateShell(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
(bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector(
shell.viewOriginTrade.selector,
fromToken,
destToken,
amount
));
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
return (_linearInterpolation(maxRet, parts), 300_000);
}
function calculateDforceSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
(bool success, bytes memory data) = address(dforceSwap).staticcall(
abi.encodeWithSelector(
dforceSwap.getAmountByInput.selector,
fromToken,
destToken,
amount
)
);
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
uint256 available = destToken.universalBalanceOf(address(dforceSwap));
if (maxRet > available) {
return (new uint256[](parts), 0);
}
return (_linearInterpolation(maxRet, parts), 160_000);
}
function _calculateUniswapFormula(uint256 fromBalance, uint256 toBalance, uint256 amount) internal pure returns(uint256) {
if (amount == 0) {
return 0;
}
return amount.mul(toBalance).mul(997).div(
fromBalance.mul(1000).add(amount.mul(997))
);
}
function _calculateUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = amounts;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange == IUniswapExchange(0)) {
return (new uint256[](rets.length), 0);
}
uint256 fromTokenBalance = fromToken.universalBalanceOf(address(fromExchange));
uint256 fromEtherBalance = address(fromExchange).balance;
for (uint i = 0; i < rets.length; i++) {
rets[i] = _calculateUniswapFormula(fromTokenBalance, fromEtherBalance, rets[i]);
}
}
if (!destToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
if (toExchange == IUniswapExchange(0)) {
return (new uint256[](rets.length), 0);
}
uint256 toEtherBalance = address(toExchange).balance;
uint256 toTokenBalance = destToken.universalBalanceOf(address(toExchange));
for (uint i = 0; i < rets.length; i++) {
rets[i] = _calculateUniswapFormula(toEtherBalance, toTokenBalance, rets[i]);
}
}
return (rets, fromToken.isETH() || destToken.isETH() ? 60_000 : 100_000);
}
function calculateUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateUniswap(
fromToken,
destToken,
_linearInterpolation(amount, parts),
flags
);
}
function _calculateUniswapWrapped(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 midTokenPrice,
uint256 flags,
uint256 gas1,
uint256 gas2
) internal view returns(uint256[] memory rets, uint256 gas) {
if (!fromToken.isETH() && destToken.isETH()) {
(rets, gas) = _calculateUniswap(
midToken,
destToken,
_linearInterpolation(amount.mul(1e18).div(midTokenPrice), parts),
flags
);
return (rets, gas + gas1);
}
else if (fromToken.isETH() && !destToken.isETH()) {
(rets, gas) = _calculateUniswap(
fromToken,
midToken,
_linearInterpolation(amount, parts),
flags
);
for (uint i = 0; i < parts; i++) {
rets[i] = rets[i].mul(midTokenPrice).div(1e18);
}
return (rets, gas + gas2);
}
return (new uint256[](parts), 0);
}
function calculateUniswapCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20 midPreToken;
if (!fromToken.isETH() && destToken.isETH()) {
midPreToken = fromToken;
}
else if (!destToken.isETH() && fromToken.isETH()) {
midPreToken = destToken;
}
if (!midPreToken.isETH()) {
ICompoundToken midToken = compoundRegistry.cTokenByToken(midPreToken);
if (midToken != ICompoundToken(0)) {
return _calculateUniswapWrapped(
fromToken,
midToken,
destToken,
amount,
parts,
midToken.exchangeRateStored(),
flags,
200_000,
200_000
);
}
}
return (new uint256[](parts), 0);
}
function calculateUniswapChai(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai && destToken.isETH() ||
fromToken.isETH() && destToken == dai)
{
return _calculateUniswapWrapped(
fromToken,
chai,
destToken,
amount,
parts,
chai.chaiPrice(),
flags,
180_000,
160_000
);
}
return (new uint256[](parts), 0);
}
function calculateUniswapAave(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20 midPreToken;
if (!fromToken.isETH() && destToken.isETH()) {
midPreToken = fromToken;
}
else if (!destToken.isETH() && fromToken.isETH()) {
midPreToken = destToken;
}
if (!midPreToken.isETH()) {
IAaveToken midToken = aaveRegistry.aTokenByToken(midPreToken);
if (midToken != IAaveToken(0)) {
return _calculateUniswapWrapped(
fromToken,
midToken,
destToken,
amount,
parts,
1e18,
flags,
310_000,
670_000
);
}
}
return (new uint256[](parts), 0);
}
function calculateKyber1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
0xff4b796265722046707200000000000000000000000000000000000000000000 // 0x63825c174ab367968EC60f061753D3bbD36A0D8F
);
}
function calculateKyber2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
0xffabcd0000000000000000000000000000000000000000000000000000000000 // 0x7a3370075a54B187d7bD5DceBf0ff2B5552d4F7D
);
}
function calculateKyber3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
0xff4f6e65426974205175616e7400000000000000000000000000000000000000 // 0x4f32BbE8dFc9efD54345Fc936f9fEF1048746fCF
);
}
function calculateKyber4(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
bytes32 reserveId = _kyberReserveIdByTokens(fromToken, destToken);
if (reserveId == 0) {
return (new uint256[](parts), 0);
}
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
reserveId
);
}
function _kyberGetRate(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags,
bytes memory hint
) private view returns(uint256) {
(, bytes memory data) = address(kyberNetworkProxy).staticcall(
abi.encodeWithSelector(
kyberNetworkProxy.getExpectedRateAfterFee.selector,
fromToken,
destToken,
amount,
(flags >> 255) * 10,
hint
)
);
return (data.length == 32) ? abi.decode(data, (uint256)) : 0;
}
function _calculateKyber(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
bytes32 reserveId
) internal view returns(uint256[] memory rets, uint256 gas) {
bytes memory fromHint;
bytes memory destHint;
{
bytes32[] memory reserveIds = new bytes32[](1);
reserveIds[0] = reserveId;
(bool success, bytes memory data) = address(kyberHintHandler).staticcall(
abi.encodeWithSelector(
kyberHintHandler.buildTokenToEthHint.selector,
fromToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
)
);
fromHint = success ? abi.decode(data, (bytes)) : bytes("");
(success, data) = address(kyberHintHandler).staticcall(
abi.encodeWithSelector(
kyberHintHandler.buildEthToTokenHint.selector,
destToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
)
);
destHint = success ? abi.decode(data, (bytes)) : bytes("");
}
uint256 fromTokenDecimals = 10 ** IERC20(fromToken).universalDecimals();
uint256 destTokenDecimals = 10 ** IERC20(destToken).universalDecimals();
rets = new uint256[](parts);
for (uint i = 0; i < parts; i++) {
if (i > 0 && rets[i - 1] == 0) {
break;
}
rets[i] = amount.mul(i + 1).div(parts);
if (!fromToken.isETH()) {
if (fromHint.length == 0) {
rets[i] = 0;
break;
}
uint256 rate = _kyberGetRate(
fromToken,
ETH_ADDRESS,
rets[i],
flags,
fromHint
);
rets[i] = rate.mul(rets[i]).div(fromTokenDecimals);
}
if (!destToken.isETH() && rets[i] > 0) {
if (destHint.length == 0) {
rets[i] = 0;
break;
}
uint256 rate = _kyberGetRate(
ETH_ADDRESS,
destToken,
rets[i],
10,
destHint
);
rets[i] = rate.mul(rets[i]).mul(destTokenDecimals).div(1e36);
}
}
return (rets, 100_000);
}
function calculateBancor(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return (new uint256[](parts), 0);
// IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
// address[] memory path = bancorFinder.buildBancorPath(
// fromToken.isETH() ? bancorEtherToken : fromToken,
// destToken.isETH() ? bancorEtherToken : destToken
// );
// rets = _linearInterpolation(amount, parts);
// for (uint i = 0; i < parts; i++) {
// (bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)(
// abi.encodeWithSelector(
// bancorNetwork.getReturnByPath.selector,
// path,
// rets[i]
// )
// );
// if (!success || data.length == 0) {
// for (; i < parts; i++) {
// rets[i] = 0;
// }
// break;
// } else {
// (uint256 ret,) = abi.decode(data, (uint256,uint256));
// rets[i] = ret;
// }
// }
// return (rets, path.length.mul(150_000));
}
function calculateOasis(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = _linearInterpolation(amount, parts);
for (uint i = 0; i < parts; i++) {
(bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)(
abi.encodeWithSelector(
oasisExchange.getBuyAmount.selector,
destToken.isETH() ? weth : destToken,
fromToken.isETH() ? weth : fromToken,
rets[i]
)
);
if (!success || data.length == 0) {
for (; i < parts; i++) {
rets[i] = 0;
}
break;
} else {
rets[i] = abi.decode(data, (uint256));
}
}
return (rets, 500_000);
}
function calculateMooniswapMany(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](amounts.length);
IMooniswap mooniswap = mooniswapRegistry.pools(
fromToken.isETH() ? ZERO_ADDRESS : fromToken,
destToken.isETH() ? ZERO_ADDRESS : destToken
);
if (mooniswap == IMooniswap(0)) {
return (rets, 0);
}
uint256 fee = mooniswap.fee();
uint256 fromBalance = mooniswap.getBalanceForAddition(fromToken.isETH() ? ZERO_ADDRESS : fromToken);
uint256 destBalance = mooniswap.getBalanceForRemoval(destToken.isETH() ? ZERO_ADDRESS : destToken);
if (fromBalance == 0 || destBalance == 0) {
return (rets, 0);
}
for (uint i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i].sub(amounts[i].mul(fee).div(1e18));
rets[i] = amount.mul(destBalance).div(
fromBalance.add(amount)
);
}
return (rets, (fromToken.isETH() || destToken.isETH()) ? 80_000 : 110_000);
}
function calculateMooniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return calculateMooniswapMany(
fromToken,
destToken,
_linearInterpolation(amount, parts)
);
}
function calculateMooniswapOverETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken.isETH() || destToken.isETH()) {
return (new uint256[](parts), 0);
}
(uint256[] memory results, uint256 gas1) = calculateMooniswap(fromToken, ZERO_ADDRESS, amount, parts, flags);
(rets, gas) = calculateMooniswapMany(ZERO_ADDRESS, destToken, results);
gas = gas.add(gas1);
}
function calculateMooniswapOverDAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai || destToken == dai) {
return (new uint256[](parts), 0);
}
(uint256[] memory results, uint256 gas1) = calculateMooniswap(fromToken, dai, amount, parts, flags);
(rets, gas) = calculateMooniswapMany(dai, destToken, results);
gas = gas.add(gas1);
}
function calculateMooniswapOverUSDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == usdc || destToken == usdc) {
return (new uint256[](parts), 0);
}
(uint256[] memory results, uint256 gas1) = calculateMooniswap(fromToken, usdc, amount, parts, flags);
(rets, gas) = calculateMooniswapMany(usdc, destToken, results);
gas = gas.add(gas1);
}
function calculateUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateUniswapV2(
fromToken,
destToken,
_linearInterpolation(amount, parts),
flags
);
}
function calculateUniswapV2ETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken.isETH() || fromToken == weth || destToken.isETH() || destToken == weth) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
weth,
destToken,
amount,
parts,
flags
);
}
function calculateUniswapV2DAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai || destToken == dai) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
dai,
destToken,
amount,
parts,
flags
);
}
function calculateUniswapV2USDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == usdc || destToken == usdc) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
usdc,
destToken,
amount,
parts,
flags
);
}
function _calculateUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](amounts.length);
IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
IERC20 destTokenReal = destToken.isETH() ? weth : destToken;
IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, destTokenReal);
if (exchange != IUniswapV2Exchange(0)) {
uint256 fromTokenBalance = fromTokenReal.universalBalanceOf(address(exchange));
uint256 destTokenBalance = destTokenReal.universalBalanceOf(address(exchange));
for (uint i = 0; i < amounts.length; i++) {
rets[i] = _calculateUniswapFormula(fromTokenBalance, destTokenBalance, amounts[i]);
}
return (rets, 50_000);
}
}
function _calculateUniswapV2OverMidToken(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = _linearInterpolation(amount, parts);
uint256 gas1;
uint256 gas2;
(rets, gas1) = _calculateUniswapV2(fromToken, midToken, rets, flags);
(rets, gas2) = _calculateUniswapV2(midToken, destToken, rets, flags);
return (rets, gas1 + gas2);
}
function _calculateNoReturn(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
this;
return (new uint256[](parts), 0);
}
}
contract OneSplitBaseWrap is IOneSplit, OneSplitRoot {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags // See constants in IOneSplit.sol
) internal {
if (fromToken == destToken) {
return;
}
_swapFloor(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _swapFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 /*flags*/ // See constants in IOneSplit.sol
) internal;
}
contract OneSplit is IOneSplit, OneSplitRoot {
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplitView) public {
oneSplitView = _oneSplitView;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags // See constants in IOneSplit.sol
) public payable returns(uint256 returnAmount) {
if (fromToken == destToken) {
return amount;
}
function(IERC20,IERC20,uint256,uint256)[DEXES_COUNT] memory reserves = [
_swapOnUniswap,
_swapOnNowhere,
_swapOnBancor,
_swapOnOasis,
_swapOnCurveCompound,
_swapOnCurveUSDT,
_swapOnCurveY,
_swapOnCurveBinance,
_swapOnCurveSynthetix,
_swapOnUniswapCompound,
_swapOnUniswapChai,
_swapOnUniswapAave,
_swapOnMooniswap,
_swapOnUniswapV2,
_swapOnUniswapV2ETH,
_swapOnUniswapV2DAI,
_swapOnUniswapV2USDC,
_swapOnCurvePAX,
_swapOnCurveRenBTC,
_swapOnCurveTBTC,
_swapOnDforceSwap,
_swapOnShell,
_swapOnMStableMUSD,
_swapOnCurveSBTC,
_swapOnBalancer1,
_swapOnBalancer2,
_swapOnBalancer3,
_swapOnKyber1,
_swapOnKyber2,
_swapOnKyber3,
_swapOnKyber4,
_swapOnMooniswapETH,
_swapOnMooniswapDAI,
_swapOnMooniswapUSDC
];
require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size");
uint256 parts = 0;
uint256 lastNonZeroIndex = 0;
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] > 0) {
parts = parts.add(distribution[i]);
lastNonZeroIndex = i;
}
}
if (parts == 0) {
if (fromToken.isETH()) {
msg.sender.transfer(msg.value);
return msg.value;
}
return amount;
}
fromToken.universalTransferFrom(msg.sender, address(this), amount);
uint256 remainingAmount = fromToken.universalBalanceOf(address(this));
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] == 0) {
continue;
}
uint256 swapAmount = amount.mul(distribution[i]).div(parts);
if (i == lastNonZeroIndex) {
swapAmount = remainingAmount;
}
remainingAmount -= swapAmount;
reserves[i](fromToken, destToken, swapAmount, flags);
}
returnAmount = destToken.universalBalanceOf(address(this));
require(returnAmount >= minReturn, "OneSplit: Return amount was not enough");
destToken.universalTransfer(msg.sender, returnAmount);
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
}
// Swap helpers
function _swapOnCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveCompound), amount);
curveCompound.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveUSDT(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveUSDT), amount);
curveUSDT.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == tusd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == tusd ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveY), amount);
curveY.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == busd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == busd ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveBinance), amount);
curveBinance.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == susd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == susd ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveSynthetix), amount);
curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurvePAX(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == pax ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == pax ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curvePAX), amount);
curvePAX.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnShell(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
fromToken.universalApprove(address(shell), amount);
shell.swapByOrigin(
address(fromToken),
address(destToken),
amount,
0,
now + 50
);
}
function _swapOnMStableMUSD(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
fromToken.universalApprove(address(musd), amount);
musd.swap(
fromToken,
destToken,
amount,
address(this)
);
}
function _swapOnCurveRenBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == renbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0);
int128 j = (destToken == renbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveRenBTC), amount);
curveRenBTC.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnCurveTBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == tbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0) +
(fromToken == hbtc ? 3 : 0);
int128 j = (destToken == tbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0) +
(destToken == hbtc ? 3 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveTBTC), amount);
curveTBTC.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnCurveSBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == renbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0) +
(fromToken == sbtc ? 3 : 0);
int128 j = (destToken == renbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0) +
(destToken == sbtc ? 3 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveSBTC), amount);
curveSBTC.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnDforceSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
fromToken.universalApprove(address(dforceSwap), amount);
dforceSwap.swap(fromToken, destToken, amount);
}
function _swapOnUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
uint256 returnAmount = amount;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange != IUniswapExchange(0)) {
fromToken.universalApprove(address(fromExchange), returnAmount);
returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now);
}
}
if (!destToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
if (toExchange != IUniswapExchange(0)) {
returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now);
}
}
}
function _swapOnUniswapCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
if (!fromToken.isETH()) {
ICompoundToken fromCompound = compoundRegistry.cTokenByToken(fromToken);
fromToken.universalApprove(address(fromCompound), amount);
fromCompound.mint(amount);
_swapOnUniswap(IERC20(fromCompound), destToken, IERC20(fromCompound).universalBalanceOf(address(this)), flags);
return;
}
if (!destToken.isETH()) {
ICompoundToken toCompound = compoundRegistry.cTokenByToken(destToken);
_swapOnUniswap(fromToken, IERC20(toCompound), amount, flags);
toCompound.redeem(IERC20(toCompound).universalBalanceOf(address(this)));
destToken.universalBalanceOf(address(this));
return;
}
}
function _swapOnUniswapChai(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
if (fromToken == dai) {
fromToken.universalApprove(address(chai), amount);
chai.join(address(this), amount);
_swapOnUniswap(IERC20(chai), destToken, IERC20(chai).universalBalanceOf(address(this)), flags);
return;
}
if (destToken == dai) {
_swapOnUniswap(fromToken, IERC20(chai), amount, flags);
chai.exit(address(this), chai.balanceOf(address(this)));
return;
}
}
function _swapOnUniswapAave(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
if (!fromToken.isETH()) {
IAaveToken fromAave = aaveRegistry.aTokenByToken(fromToken);
fromToken.universalApprove(aave.core(), amount);
aave.deposit(fromToken, amount, 1101);
_swapOnUniswap(IERC20(fromAave), destToken, IERC20(fromAave).universalBalanceOf(address(this)), flags);
return;
}
if (!destToken.isETH()) {
IAaveToken toAave = aaveRegistry.aTokenByToken(destToken);
_swapOnUniswap(fromToken, IERC20(toAave), amount, flags);
toAave.redeem(toAave.balanceOf(address(this)));
return;
}
}
function _swapOnMooniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
IMooniswap mooniswap = mooniswapRegistry.pools(
fromToken.isETH() ? ZERO_ADDRESS : fromToken,
destToken.isETH() ? ZERO_ADDRESS : destToken
);
fromToken.universalApprove(address(mooniswap), amount);
mooniswap.swap.value(fromToken.isETH() ? amount : 0)(
fromToken.isETH() ? ZERO_ADDRESS : fromToken,
destToken.isETH() ? ZERO_ADDRESS : destToken,
amount,
0,
0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5
);
}
function _swapOnMooniswapETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnMooniswap(fromToken, ZERO_ADDRESS, amount, flags);
_swapOnMooniswap(ZERO_ADDRESS, destToken, address(this).balance, flags);
}
function _swapOnMooniswapDAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnMooniswap(fromToken, dai, amount, flags);
_swapOnMooniswap(dai, destToken, dai.balanceOf(address(this)), flags);
}
function _swapOnMooniswapUSDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnMooniswap(fromToken, usdc, amount, flags);
_swapOnMooniswap(usdc, destToken, usdc.balanceOf(address(this)), flags);
}
function _swapOnNowhere(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 /*flags*/
) internal {
revert("This source was deprecated");
}
function _swapOnKyber1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
0xff4b796265722046707200000000000000000000000000000000000000000000
);
}
function _swapOnKyber2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
0xffabcd0000000000000000000000000000000000000000000000000000000000
);
}
function _swapOnKyber3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
0xff4f6e65426974205175616e7400000000000000000000000000000000000000
);
}
function _swapOnKyber4(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
_kyberReserveIdByTokens(fromToken, destToken)
);
}
function _swapOnKyber(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags,
bytes32 reserveId
) internal {
uint256 returnAmount = amount;
bytes32[] memory reserveIds = new bytes32[](1);
reserveIds[0] = reserveId;
if (!fromToken.isETH()) {
bytes memory fromHint = kyberHintHandler.buildTokenToEthHint(
fromToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
);
fromToken.universalApprove(address(kyberNetworkProxy), amount);
returnAmount = kyberNetworkProxy.tradeWithHintAndFee(
fromToken,
returnAmount,
ETH_ADDRESS,
address(this),
uint256(-1),
0,
0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5,
(flags >> 255) * 10,
fromHint
);
}
if (!destToken.isETH()) {
bytes memory destHint = kyberHintHandler.buildEthToTokenHint(
destToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
);
returnAmount = kyberNetworkProxy.tradeWithHintAndFee.value(returnAmount)(
ETH_ADDRESS,
returnAmount,
destToken,
address(this),
uint256(-1),
0,
0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5,
(flags >> 255) * 10,
destHint
);
}
}
function _swapOnBancor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
address[] memory path = bancorNetworkPathFinder.generatePath(
fromToken.isETH() ? bancorEtherToken : fromToken,
destToken.isETH() ? bancorEtherToken : destToken
);
fromToken.universalApprove(address(bancorNetwork), amount);
bancorNetwork.convert.value(fromToken.isETH() ? amount : 0)(path, amount, 1);
}
function _swapOnOasis(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
IERC20 approveToken = fromToken.isETH() ? weth : fromToken;
approveToken.universalApprove(address(oasisExchange), amount);
oasisExchange.sellAllAmount(
fromToken.isETH() ? weth : fromToken,
amount,
destToken.isETH() ? weth : destToken,
1
);
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnUniswapV2Internal(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal returns(uint256 returnAmount) {
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
IERC20 toTokenReal = destToken.isETH() ? weth : destToken;
IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal);
bool needSync;
bool needSkim;
(returnAmount, needSync, needSkim) = exchange.getReturn(fromTokenReal, toTokenReal, amount);
if (needSync) {
exchange.sync();
}
else if (needSkim) {
exchange.skim(0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5);
}
fromTokenReal.universalTransfer(address(exchange), amount);
if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) {
exchange.swap(0, returnAmount, address(this), "");
} else {
exchange.swap(returnAmount, 0, address(this), "");
}
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnUniswapV2OverMid(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2Internal(
midToken,
destToken,
_swapOnUniswapV2Internal(
fromToken,
midToken,
amount,
flags
),
flags
);
}
function _swapOnUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2Internal(
fromToken,
destToken,
amount,
flags
);
}
function _swapOnUniswapV2ETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2OverMid(
fromToken,
weth,
destToken,
amount,
flags
);
}
function _swapOnUniswapV2DAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2OverMid(
fromToken,
dai,
destToken,
amount,
flags
);
}
function _swapOnUniswapV2USDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2OverMid(
fromToken,
usdc,
destToken,
amount,
flags
);
}
function _swapOnBalancerX(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/,
uint256 poolIndex
) internal {
address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
address(fromToken.isETH() ? weth : fromToken),
address(destToken.isETH() ? weth : destToken),
poolIndex + 1
);
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
(fromToken.isETH() ? weth : fromToken).universalApprove(pools[poolIndex], amount);
IBalancerPool(pools[poolIndex]).swapExactAmountIn(
fromToken.isETH() ? weth : fromToken,
amount,
destToken.isETH() ? weth : destToken,
0,
uint256(-1)
);
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnBalancer1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnBalancerX(fromToken, destToken, amount, flags, 0);
}
function _swapOnBalancer2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnBalancerX(fromToken, destToken, amount, flags, 1);
}
function _swapOnBalancer3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnBalancerX(fromToken, destToken, amount, flags, 2);
}
}
// File: contracts/OneSplitCompound.sol
pragma solidity ^0.5.0;
contract OneSplitCompoundView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _compoundGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _compoundGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
if (underlying != IERC20(0)) {
uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored();
(returnAmount, estimateGasAmount, distribution) = _compoundGetExpectedReturn(
underlying,
destToken,
amount.mul(compoundRate).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
if (underlying != IERC20(0)) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
uint256 compoundRate = ICompoundToken(address(destToken)).exchangeRateStored();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice.mul(compoundRate).div(1e18)
);
return (returnAmount.mul(1e18).div(compoundRate), estimateGasAmount + 430_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitCompound is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_compoundSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _compoundSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
if (underlying != IERC20(0)) {
ICompoundToken(address(fromToken)).redeem(amount);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return _compoundSwap(
underlying,
destToken,
underlyingAmount,
distribution,
flags
);
}
underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
if (underlying != IERC20(0)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
cETH.mint.value(underlyingAmount)();
} else {
underlying.universalApprove(address(destToken), underlyingAmount);
ICompoundToken(address(destToken)).mint(underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IFulcrum.sol
pragma solidity ^0.5.0;
contract IFulcrumToken is IERC20 {
function tokenPrice() external view returns (uint256);
function loanTokenAddress() external view returns (address);
function mintWithEther(address receiver) external payable returns (uint256 mintAmount);
function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
function burnToEther(address receiver, uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
}
// File: contracts/OneSplitFulcrum.sol
pragma solidity ^0.5.0;
contract OneSplitFulcrumBase {
using UniversalERC20 for IERC20;
function _isFulcrumToken(IERC20 token) internal view returns(IERC20) {
if (token.isETH()) {
return IERC20(-1);
}
(bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSignature(
"name()"
));
if (!success) {
return IERC20(-1);
}
bool foundBZX = false;
for (uint i = 0; i + 6 < data.length; i++) {
if (data[i + 0] == "F" &&
data[i + 1] == "u" &&
data[i + 2] == "l" &&
data[i + 3] == "c" &&
data[i + 4] == "r" &&
data[i + 5] == "u" &&
data[i + 6] == "m")
{
foundBZX = true;
break;
}
}
if (!foundBZX) {
return IERC20(-1);
}
(success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
IFulcrumToken(address(token)).loanTokenAddress.selector
));
if (!success) {
return IERC20(-1);
}
return abi.decode(data, (IERC20));
}
}
contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _fulcrumGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _fulcrumGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice();
(returnAmount, estimateGasAmount, distribution) = _fulcrumGetExpectedReturn(
underlying,
destToken,
amount.mul(fulcrumRate).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 381_000, distribution);
}
underlying = _isFulcrumToken(destToken);
if (underlying != IERC20(-1)) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
uint256 fulcrumRate = IFulcrumToken(address(destToken)).tokenPrice();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice.mul(fulcrumRate).div(1e18)
);
return (returnAmount.mul(1e18).div(fulcrumRate), estimateGasAmount + 354_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_fulcrumSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _fulcrumSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
if (underlying.isETH()) {
IFulcrumToken(address(fromToken)).burnToEther(address(this), amount);
} else {
IFulcrumToken(address(fromToken)).burn(address(this), amount);
}
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return super._swap(
underlying,
destToken,
underlyingAmount,
distribution,
flags
);
}
underlying = _isFulcrumToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
IFulcrumToken(address(destToken)).mintWithEther.value(underlyingAmount)(address(this));
} else {
underlying.universalApprove(address(destToken), underlyingAmount);
IFulcrumToken(address(destToken)).mint(address(this), underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitChai.sol
pragma solidity ^0.5.0;
contract OneSplitChaiView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
dai,
destToken,
chai.chaiToDai(amount),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 197_000, distribution);
}
if (destToken == IERC20(chai)) {
uint256 price = chai.chaiPrice();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
dai,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice.mul(1e18).div(price)
);
return (returnAmount.mul(price).div(1e18), estimateGasAmount + 168_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitChai is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
chai.exit(address(this), amount);
return super._swap(
dai,
destToken,
dai.balanceOf(address(this)),
distribution,
flags
);
}
if (destToken == IERC20(chai)) {
super._swap(
fromToken,
dai,
amount,
distribution,
flags
);
uint256 daiBalance = dai.balanceOf(address(this));
dai.universalApprove(address(chai), daiBalance);
chai.join(address(this), daiBalance);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IBdai.sol
pragma solidity ^0.5.0;
contract IBdai is IERC20 {
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/OneSplitBdai.sol
pragma solidity ^0.5.0;
contract OneSplitBdaiBase {
IBdai internal constant bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8);
IERC20 internal constant btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f);
}
contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
dai,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 227_000, distribution);
}
if (destToken == IERC20(bdai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
dai,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
bdai.exit(amount);
uint256 btuBalance = btu.balanceOf(address(this));
if (btuBalance > 0) {
(,uint256[] memory btuDistribution) = getExpectedReturn(
btu,
destToken,
btuBalance,
1,
flags
);
_swap(
btu,
destToken,
btuBalance,
btuDistribution,
flags
);
}
return super._swap(
dai,
destToken,
amount,
distribution,
flags
);
}
if (destToken == IERC20(bdai)) {
super._swap(fromToken, dai, amount, distribution, flags);
uint256 daiBalance = dai.balanceOf(address(this));
dai.universalApprove(address(bdai), daiBalance);
bdai.join(daiBalance);
return;
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIearn.sol
pragma solidity ^0.5.0;
contract IIearn is IERC20 {
function token() external view returns(IERC20);
function calcPoolValueInToken() external view returns(uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/OneSplitIearn.sol
pragma solidity ^0.5.0;
contract OneSplitIearnBase {
function _yTokens() internal pure returns(IIearn[13] memory) {
return [
IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01),
IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9),
IIearn(0x73a052500105205d34Daf004eAb301916DA8190f),
IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D),
IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e),
IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600),
IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE),
IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32),
IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447),
IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951),
IIearn(0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc),
IIearn(0x9777d7E2b60bB01759D0E2f8be2095df444cb07E),
IIearn(0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59)
];
}
}
contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _iearnGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _iearnGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IEARN)) {
IIearn[13] memory yTokens = _yTokens();
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
(returnAmount, estimateGasAmount, distribution) = _iearnGetExpectedReturn(
yTokens[i].token(),
destToken,
amount
.mul(yTokens[i].calcPoolValueInToken())
.div(yTokens[i].totalSupply()),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 260_000, distribution);
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (destToken == IERC20(yTokens[i])) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
IERC20 token = yTokens[i].token();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
token,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice
.mul(yTokens[i].calcPoolValueInToken())
.div(yTokens[i].totalSupply())
);
return(
returnAmount
.mul(yTokens[i].totalSupply())
.div(yTokens[i].calcPoolValueInToken()),
estimateGasAmount + 743_000,
distribution
);
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_iearnSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _iearnSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_IEARN)) {
IIearn[13] memory yTokens = _yTokens();
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
yTokens[i].withdraw(amount);
_iearnSwap(underlying, destToken, underlying.balanceOf(address(this)), distribution, flags);
return;
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (destToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
uint256 underlyingBalance = underlying.balanceOf(address(this));
underlying.universalApprove(address(yTokens[i]), underlyingBalance);
yTokens[i].deposit(underlyingBalance);
return;
}
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIdle.sol
pragma solidity ^0.5.0;
contract IIdle is IERC20 {
function token()
external view returns (IERC20);
function tokenPrice()
external view returns (uint256);
function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 mintedTokens);
function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 redeemedTokens);
}
// File: contracts/OneSplitIdle.sol
pragma solidity ^0.5.0;
contract OneSplitIdleBase {
function _idleTokens() internal pure returns(IIdle[8] memory) {
// https://developers.idle.finance/contracts-and-codebase
return [
// V3
IIdle(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934),
IIdle(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6),
IIdle(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D),
IIdle(0x1846bdfDB6A0f5c473dEc610144513bd071999fB),
IIdle(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C),
IIdle(0x42740698959761BAF1B06baa51EfBD88CB1D862B),
// V2
IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD),
IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991)
];
}
}
contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _idleGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _idleGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
IIdle[8] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
(returnAmount, estimateGasAmount, distribution) = _idleGetExpectedReturn(
tokens[i].token(),
destToken,
amount.mul(tokens[i].tokenPrice()).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 2_400_000, distribution);
}
}
for (uint i = 0; i < tokens.length; i++) {
if (destToken == IERC20(tokens[i])) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
uint256 _price = tokens[i].tokenPrice();
IERC20 token = tokens[i].token();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
token,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice.mul(_price).div(1e18)
);
return (returnAmount.mul(1e18).div(_price), estimateGasAmount + 1_300_000, distribution);
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_idleSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _idleSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
IIdle[8] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0));
_idleSwap(underlying, destToken, minted, distribution, flags);
return;
}
}
for (uint i = 0; i < tokens.length; i++) {
if (destToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
uint256 underlyingBalance = underlying.balanceOf(address(this));
underlying.universalApprove(address(tokens[i]), underlyingBalance);
tokens[i].mintIdleToken(underlyingBalance, new uint256[](0));
return;
}
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/OneSplitAave.sol
pragma solidity ^0.5.0;
contract OneSplitAaveView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _aaveGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _aaveGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
if (underlying != IERC20(0)) {
(returnAmount, estimateGasAmount, distribution) = _aaveGetExpectedReturn(
underlying,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 670_000, distribution);
}
underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
if (underlying != IERC20(0)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 310_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitAave is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_aaveSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _aaveSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
if (underlying != IERC20(0)) {
IAaveToken(address(fromToken)).redeem(amount);
return _aaveSwap(
underlying,
destToken,
amount,
distribution,
flags
);
}
underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
if (underlying != IERC20(0)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
underlying.universalApprove(aave.core(), underlyingAmount);
aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)(
underlying.isETH() ? ETH_ADDRESS : underlying,
underlyingAmount,
1101
);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitWeth.sol
pragma solidity ^0.5.0;
contract OneSplitWethView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _wethGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _wethGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == weth || fromToken == bancorEtherToken) {
return super.getExpectedReturnWithGas(ETH_ADDRESS, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice);
}
if (destToken == weth || destToken == bancorEtherToken) {
return super.getExpectedReturnWithGas(fromToken, ETH_ADDRESS, amount, parts, flags, destTokenEthPriceTimesGasPrice);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitWeth is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_wethSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _wethSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == weth) {
weth.withdraw(weth.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
destToken,
amount,
distribution,
flags
);
return;
}
if (fromToken == bancorEtherToken) {
bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
destToken,
amount,
distribution,
flags
);
return;
}
if (destToken == weth) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
weth.deposit.value(address(this).balance)();
return;
}
if (destToken == bancorEtherToken) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
bancorEtherToken.deposit.value(address(this).balance)();
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitMStable.sol
pragma solidity ^0.5.0;
contract OneSplitMStableView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
if (fromToken == IERC20(musd)) {
{
(bool valid1,, uint256 res1,) = musd_helper.getRedeemValidity(musd, amount, destToken);
if (valid1) {
return (res1, 300_000, new uint256[](DEXES_COUNT));
}
}
(bool valid,, address token) = musd_helper.suggestRedeemAsset(musd);
if (valid) {
(,, returnAmount,) = musd_helper.getRedeemValidity(musd, amount, IERC20(token));
if (IERC20(token) != destToken) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
IERC20(token),
destToken,
returnAmount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
} else {
distribution = new uint256[](DEXES_COUNT);
}
return (returnAmount, estimateGasAmount + 300_000, distribution);
}
}
if (destToken == IERC20(musd)) {
if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
(,, returnAmount) = musd.getSwapOutput(fromToken, destToken, amount);
return (returnAmount, 300_000, new uint256[](DEXES_COUNT));
}
else {
IERC20 _destToken = destToken;
(bool valid,, address token) = musd_helper.suggestMintAsset(_destToken);
if (valid) {
if (IERC20(token) != fromToken) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
IERC20(token),
amount,
parts,
flags,
_scaleDestTokenEthPriceTimesGasPrice(
_destToken,
IERC20(token),
destTokenEthPriceTimesGasPrice
)
);
} else {
returnAmount = amount;
}
(,, returnAmount) = musd.getSwapOutput(IERC20(token), _destToken, returnAmount);
return (returnAmount, estimateGasAmount + 300_000, distribution);
}
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitMStable is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
if (fromToken == IERC20(musd)) {
if (destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd) {
(,,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, destToken);
musd.redeem(
destToken,
result
);
}
else {
(,,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, dai);
musd.redeem(
dai,
result
);
super._swap(
dai,
destToken,
dai.balanceOf(address(this)),
distribution,
flags
);
}
return;
}
if (destToken == IERC20(musd)) {
if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
fromToken.universalApprove(address(musd), amount);
musd.swap(
fromToken,
destToken,
amount,
address(this)
);
}
else {
super._swap(
fromToken,
dai,
amount,
distribution,
flags
);
musd.swap(
dai,
destToken,
dai.balanceOf(address(this)),
address(this)
);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IDMM.sol
pragma solidity ^0.5.0;
interface IDMMController {
function getUnderlyingTokenForDmm(IERC20 token) external view returns(IERC20);
}
contract IDMM is IERC20 {
function getCurrentExchangeRate() public view returns(uint256);
function mint(uint256 underlyingAmount) public returns(uint256);
function redeem(uint256 amount) public returns(uint256);
}
// File: contracts/OneSplitDMM.sol
pragma solidity ^0.5.0;
contract OneSplitDMMBase {
IDMMController internal constant _dmmController = IDMMController(0x4CB120Dd1D33C9A3De8Bc15620C7Cd43418d77E2);
function _getDMMUnderlyingToken(IERC20 token) internal view returns(IERC20) {
(bool success, bytes memory data) = address(_dmmController).staticcall(
abi.encodeWithSelector(
_dmmController.getUnderlyingTokenForDmm.selector,
token
)
);
if (!success || data.length == 0) {
return IERC20(-1);
}
return abi.decode(data, (IERC20));
}
function _getDMMExchangeRate(IDMM dmm) internal view returns(uint256) {
(bool success, bytes memory data) = address(dmm).staticcall(
abi.encodeWithSelector(
dmm.getCurrentExchangeRate.selector
)
);
if (!success || data.length == 0) {
return 0;
}
return abi.decode(data, (uint256));
}
}
contract OneSplitDMMView is OneSplitViewWrapBase, OneSplitDMMBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _dmmGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _dmmGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
IERC20 underlying = _getDMMUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
if (underlying == weth) {
underlying = ETH_ADDRESS;
}
IERC20 _fromToken = fromToken;
(returnAmount, estimateGasAmount, distribution) = _dmmGetExpectedReturn(
underlying,
destToken,
amount.mul(_getDMMExchangeRate(IDMM(address(_fromToken)))).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
underlying = _getDMMUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
if (underlying == weth) {
underlying = ETH_ADDRESS;
}
uint256 price = _getDMMExchangeRate(IDMM(address(destToken)));
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice.mul(price).div(1e18)
);
return (
returnAmount.mul(1e18).div(price),
estimateGasAmount + 430_000,
distribution
);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitDMM is OneSplitBaseWrap, OneSplitDMMBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_dmmSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _dmmSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
IERC20 underlying = _getDMMUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
IDMM(address(fromToken)).redeem(amount);
uint256 balance = underlying.universalBalanceOf(address(this));
if (underlying == weth) {
weth.withdraw(balance);
}
_dmmSwap(
(underlying == weth) ? ETH_ADDRESS : underlying,
destToken,
balance,
distribution,
flags
);
}
underlying = _getDMMUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
(underlying == weth) ? ETH_ADDRESS : underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = ((underlying == weth) ? ETH_ADDRESS : underlying).universalBalanceOf(address(this));
if (underlying == weth) {
weth.deposit.value(underlyingAmount);
}
underlying.universalApprove(address(destToken), underlyingAmount);
IDMM(address(destToken)).mint(underlyingAmount);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitMooniswapPoolToken.sol
pragma solidity ^0.5.0;
contract OneSplitMooniswapTokenBase {
using SafeMath for uint256;
using Math for uint256;
using UniversalERC20 for IERC20;
struct TokenInfo {
IERC20 token;
uint256 reserve;
}
struct PoolDetails {
TokenInfo[2] tokens;
uint256 totalSupply;
}
function _getPoolDetails(IMooniswap pool) internal view returns (PoolDetails memory details) {
for (uint i = 0; i < 2; i++) {
IERC20 token = pool.tokens(i);
details.tokens[i] = TokenInfo({
token: token,
reserve: token.universalBalanceOf(address(pool))
});
}
details.totalSupply = IERC20(address(pool)).totalSupply();
}
}
contract OneSplitMooniswapTokenView is OneSplitViewWrapBase, OneSplitMooniswapTokenBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns (
uint256 returnAmount,
uint256,
uint256[] memory distribution
)
{
if (fromToken.eq(toToken)) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_MOONISWAP_POOL_TOKEN)) {
bool isPoolTokenFrom = mooniswapRegistry.isPool(address(fromToken));
bool isPoolTokenTo = mooniswapRegistry.isPool(address(toToken));
if (isPoolTokenFrom && isPoolTokenTo) {
(
uint256 returnETHAmount,
uint256[] memory poolTokenFromDistribution
) = _getExpectedReturnFromMooniswapPoolToken(
fromToken,
ETH_ADDRESS,
amount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
(
uint256 returnPoolTokenToAmount,
uint256[] memory poolTokenToDistribution
) = _getExpectedReturnToMooniswapPoolToken(
ETH_ADDRESS,
toToken,
returnETHAmount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
for (uint i = 0; i < poolTokenToDistribution.length; i++) {
poolTokenFromDistribution[i] |= poolTokenToDistribution[i] << 128;
}
return (returnPoolTokenToAmount, 0, poolTokenFromDistribution);
}
if (isPoolTokenFrom) {
(returnAmount, distribution) = _getExpectedReturnFromMooniswapPoolToken(
fromToken,
toToken,
amount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
return (returnAmount, 0, distribution);
}
if (isPoolTokenTo) {
(returnAmount, distribution) = _getExpectedReturnToMooniswapPoolToken(
fromToken,
toToken,
amount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
return (returnAmount, 0, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
toToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnFromMooniswapPoolToken(
IERC20 poolToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
PoolDetails memory details = _getPoolDetails(IMooniswap(address(poolToken)));
for (uint i = 0; i < 2; i++) {
uint256 exchangeAmount = amount
.mul(details.tokens[i].reserve)
.div(details.totalSupply);
if (toToken.eq(details.tokens[i].token)) {
returnAmount = returnAmount.add(exchangeAmount);
continue;
}
(uint256 ret, ,uint256[] memory dist) = super.getExpectedReturnWithGas(
details.tokens[i].token,
toToken,
exchangeAmount,
parts,
flags,
0
);
returnAmount = returnAmount.add(ret);
for (uint j = 0; j < distribution.length; j++) {
distribution[j] |= dist[j] << (i * 8);
}
}
return (returnAmount, distribution);
}
function _getExpectedReturnToMooniswapPoolToken(
IERC20 fromToken,
IERC20 poolToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
PoolDetails memory details = _getPoolDetails(IMooniswap(address(poolToken)));
// will overwritten to liquidity amounts
uint256[2] memory amounts;
amounts[0] = amount.div(2);
amounts[1] = amount.sub(amounts[0]);
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < 2; i++) {
if (fromToken.eq(details.tokens[i].token)) {
continue;
}
(amounts[i], ,dist) = super.getExpectedReturnWithGas(
fromToken,
details.tokens[i].token,
amounts[i],
parts,
flags,
0
);
for (uint j = 0; j < distribution.length; j++) {
distribution[j] |= dist[j] << (i * 8);
}
}
returnAmount = uint256(-1);
for (uint i = 0; i < 2; i++) {
returnAmount = Math.min(
returnAmount,
details.totalSupply.mul(amounts[i]).div(details.tokens[i].reserve)
);
}
return (
returnAmount,
distribution
);
}
}
contract OneSplitMooniswapToken is OneSplitBaseWrap, OneSplitMooniswapTokenBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken.eq(toToken)) {
return;
}
if (!flags.check(FLAG_DISABLE_MOONISWAP_POOL_TOKEN)) {
bool isPoolTokenFrom = mooniswapRegistry.isPool(address(fromToken));
bool isPoolTokenTo = mooniswapRegistry.isPool(address(toToken));
if (isPoolTokenFrom && isPoolTokenTo) {
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] & ((1 << 128) - 1);
}
uint256 ethBalanceBefore = ETH_ADDRESS.universalBalanceOf(address(this));
_swapFromMooniswapToken(
fromToken,
ETH_ADDRESS,
amount,
dist,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] >> 128;
}
uint256 ethBalanceAfter = ETH_ADDRESS.universalBalanceOf(address(this));
return _swapToMooniswapToken(
ETH_ADDRESS,
toToken,
ethBalanceAfter.sub(ethBalanceBefore),
dist,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
}
if (isPoolTokenFrom) {
return _swapFromMooniswapToken(
fromToken,
toToken,
amount,
distribution,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
}
if (isPoolTokenTo) {
return _swapToMooniswapToken(
fromToken,
toToken,
amount,
distribution,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _swapFromMooniswapToken(
IERC20 poolToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
IERC20[2] memory tokens = [
IMooniswap(address(poolToken)).tokens(0),
IMooniswap(address(poolToken)).tokens(1)
];
IMooniswap(address(poolToken)).withdraw(
amount,
new uint256[](0)
);
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < 2; i++) {
if (toToken.eq(tokens[i])) {
continue;
}
for (uint j = 0; j < distribution.length; j++) {
dist[j] = (distribution[j] >> (i * 8)) & 0xFF;
}
super._swap(
tokens[i],
toToken,
tokens[i].universalBalanceOf(address(this)),
dist,
flags
);
}
}
function _swapToMooniswapToken(
IERC20 fromToken,
IERC20 poolToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
IERC20[2] memory tokens = [
IMooniswap(address(poolToken)).tokens(0),
IMooniswap(address(poolToken)).tokens(1)
];
// will overwritten to liquidity amounts
uint256[] memory amounts = new uint256[](2);
amounts[0] = amount.div(2);
amounts[1] = amount.sub(amounts[0]);
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < 2; i++) {
if (fromToken.eq(tokens[i])) {
continue;
}
for (uint j = 0; j < distribution.length; j++) {
dist[j] = (distribution[j] >> (i * 8)) & 0xFF;
}
super._swap(
fromToken,
tokens[i],
amounts[i],
dist,
flags
);
amounts[i] = tokens[i].universalBalanceOf(address(this));
tokens[i].universalApprove(address(poolToken), amounts[i]);
}
uint256 ethValue = (tokens[0].isETH() ? amounts[0] : 0) + (tokens[1].isETH() ? amounts[1] : 0);
IMooniswap(address(poolToken)).deposit.value(ethValue)(
amounts,
new uint256[](2)
);
for (uint i = 0; i < 2; i++) {
tokens[i].universalTransfer(
msg.sender,
tokens[i].universalBalanceOf(address(this))
);
}
}
}
// File: contracts/OneSplit.sol
pragma solidity ^0.5.0;
contract OneSplitViewWrap is
OneSplitViewWrapBase,
OneSplitMStableView,
OneSplitChaiView,
OneSplitBdaiView,
OneSplitAaveView,
OneSplitFulcrumView,
OneSplitCompoundView,
OneSplitIearnView,
OneSplitIdleView,
OneSplitWethView,
OneSplitDMMView,
OneSplitMooniswapTokenView
{
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplit) public {
oneSplitView = _oneSplit;
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnRespectingGasFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitWrap is
OneSplitBaseWrap,
OneSplitMStable,
OneSplitChai,
OneSplitBdai,
OneSplitAave,
OneSplitFulcrum,
OneSplitCompound,
OneSplitIearn,
OneSplitIdle,
OneSplitWeth,
OneSplitDMM,
OneSplitMooniswapToken
{
IOneSplitView public oneSplitView;
IOneSplit public oneSplit;
constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public {
oneSplitView = _oneSplitView;
oneSplit = _oneSplit;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
uint256[] memory dist;
returnAmounts = new uint256[](tokens.length - 1);
for (uint i = 1; i < tokens.length; i++) {
if (tokens[i - 1] == tokens[i]) {
returnAmounts[i - 1] = (i == 1) ? amount : returnAmounts[i - 2];
continue;
}
IERC20[] memory _tokens = tokens;
(
returnAmounts[i - 1],
amount,
dist
) = getExpectedReturnWithGas(
_tokens[i - 1],
_tokens[i],
(i == 1) ? amount : returnAmounts[i - 2],
parts[i - 1],
flags[i - 1],
destTokenEthPriceTimesGasPrices[i - 1]
);
estimateGasAmount = estimateGasAmount.add(amount);
if (distribution.length == 0) {
distribution = new uint256[](dist.length);
}
for (uint j = 0; j < distribution.length; j++) {
distribution[j] = distribution[j].add(dist[j] << (8 * (i - 1)));
}
}
}
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable returns(uint256 returnAmount) {
fromToken.universalTransferFrom(msg.sender, address(this), amount);
uint256 confirmed = fromToken.universalBalanceOf(address(this));
_swap(fromToken, destToken, confirmed, distribution, flags);
returnAmount = destToken.universalBalanceOf(address(this));
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
destToken.universalTransfer(msg.sender, returnAmount);
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
}
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
) public payable returns(uint256 returnAmount) {
tokens[0].universalTransferFrom(msg.sender, address(this), amount);
returnAmount = tokens[0].universalBalanceOf(address(this));
for (uint i = 1; i < tokens.length; i++) {
if (tokens[i - 1] == tokens[i]) {
continue;
}
uint256[] memory dist = new uint256[](distribution.length);
for (uint j = 0; j < distribution.length; j++) {
dist[j] = (distribution[j] >> (8 * (i - 1))) & 0xFF;
}
_swap(
tokens[i - 1],
tokens[i],
returnAmount,
dist,
flags[i - 1]
);
returnAmount = tokens[i].universalBalanceOf(address(this));
tokens[i - 1].universalTransfer(msg.sender, tokens[i - 1].universalBalanceOf(address(this)));
}
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
tokens[tokens.length - 1].universalTransfer(msg.sender, returnAmount);
}
function _swapFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
fromToken.universalApprove(address(oneSplit), amount);
oneSplit.swap.value(fromToken.isETH() ? amount : 0)(
fromToken,
destToken,
amount,
0,
distribution,
flags
);
}
}File 4 of 14: UniswapV2Pair
// File: contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IUniswapV2ERC20.sol
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/UniswapV2ERC20.sol
pragma solidity =0.5.16;
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/libraries/Math.sol
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IUniswapV2Callee.sol
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: contracts/UniswapV2Pair.sol
pragma solidity =0.5.16;
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}File 5 of 14: YFV
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
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;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract YFV is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
constructor () public ERC20Detailed("YFValue", "YFV", 18) {
governance = msg.sender;
}
function mint(address account, uint256 amount) public {
require(minters[msg.sender], "!minter");
_mint(account, amount);
}
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function addMinter(address _minter) public {
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function removeMinter(address _minter) public {
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
}File 6 of 14: OneSplitWrap
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IOneSplit.sol
pragma solidity ^0.5.0;
//
// [ msg.sender ]
// | |
// | |
// \_/
// +---------------+ ________________________________
// | OneSplitAudit | _______________________________ \
// +---------------+ \ \
// | | ______________ | | (staticcall)
// | | / ____________ \ | |
// | | (call) / / \ \ | |
// | | / / | | | |
// \_/ | | \_/ \_/
// +--------------+ | | +----------------------+
// | OneSplitWrap | | | | OneSplitViewWrap |
// +--------------+ | | +----------------------+
// | | | | | |
// | | (delegatecall) | | (staticcall) | | (staticcall)
// \_/ | | \_/
// +--------------+ | | +------------------+
// | OneSplit | | | | OneSplitView |
// +--------------+ | | +------------------+
// | | / /
// \ \________________/ /
// \__________________/
//
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000;
uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
)
public
payable
returns(uint256 returnAmount);
}
contract IOneSplitMulti is IOneSplit {
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
)
public
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/interface/IUniswapExchange.sol
pragma solidity ^0.5.0;
interface IUniswapExchange {
function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought);
function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
external
payable
returns (uint256 tokensBought);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
external
returns (uint256 ethBought);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddr
) external returns (uint256 tokensBought);
}
// File: contracts/interface/IUniswapFactory.sol
pragma solidity ^0.5.0;
interface IUniswapFactory {
function getExchange(IERC20 token) external view returns (IUniswapExchange exchange);
}
// File: contracts/interface/IKyberNetworkContract.sol
pragma solidity ^0.5.0;
interface IKyberNetworkContract {
function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless)
external
view
returns (address reserve, uint256 rate);
}
// File: contracts/interface/IKyberNetworkProxy.sol
pragma solidity ^0.5.0;
interface IKyberNetworkProxy {
function getExpectedRateAfterFee(
IERC20 src,
IERC20 dest,
uint256 srcQty,
uint256 platformFeeBps,
bytes calldata hint
) external view returns (uint256 expectedRate);
function tradeWithHintAndFee(
IERC20 src,
uint256 srcAmount,
IERC20 dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable platformWallet,
uint256 platformFeeBps,
bytes calldata hint
) external payable returns (uint256 destAmount);
function kyberNetworkContract() external view returns (IKyberNetworkContract);
// TODO: Limit usage by tx.gasPrice
// function maxGasPrice() external view returns (uint256);
// TODO: Limit usage by user cap
// function getUserCapInWei(address user) external view returns (uint256);
// function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256);
}
// File: contracts/interface/IKyberStorage.sol
pragma solidity ^0.5.0;
interface IKyberStorage {
function getReserveIdsPerTokenSrc(
IERC20 token
) external view returns (bytes32[] memory);
}
// File: contracts/interface/IKyberHintHandler.sol
pragma solidity ^0.5.0;
interface IKyberHintHandler {
enum TradeType {
BestOfAll,
MaskIn,
MaskOut,
Split
}
function buildTokenToEthHint(
IERC20 tokenSrc,
TradeType tokenToEthType,
bytes32[] calldata tokenToEthReserveIds,
uint256[] calldata tokenToEthSplits
) external view returns (bytes memory hint);
function buildEthToTokenHint(
IERC20 tokenDest,
TradeType ethToTokenType,
bytes32[] calldata ethToTokenReserveIds,
uint256[] calldata ethToTokenSplits
) external view returns (bytes memory hint);
}
// File: contracts/interface/IBancorNetwork.sol
pragma solidity ^0.5.0;
interface IBancorNetwork {
function getReturnByPath(address[] calldata path, uint256 amount)
external
view
returns (uint256 returnAmount, uint256 conversionFee);
function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn)
external
returns (uint256);
function convert(address[] calldata path, uint256 amount, uint256 minReturn)
external
payable
returns (uint256);
}
// File: contracts/interface/IBancorContractRegistry.sol
pragma solidity ^0.5.0;
contract IBancorContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
// File: contracts/interface/IBancorNetworkPathFinder.sol
pragma solidity ^0.5.0;
interface IBancorNetworkPathFinder {
function generatePath(IERC20 sourceToken, IERC20 targetToken)
external
view
returns (address[] memory);
}
// File: contracts/interface/IBancorConverterRegistry.sol
pragma solidity ^0.5.0;
interface IBancorConverterRegistry {
function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken)
external view returns(uint256);
function getConvertibleTokenSmartTokens(IERC20 convertibleToken)
external view returns(address[] memory);
function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index)
external view returns(address);
function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value)
external view returns(bool);
}
// File: contracts/interface/IBancorEtherToken.sol
pragma solidity ^0.5.0;
contract IBancorEtherToken is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/IBancorFinder.sol
pragma solidity ^0.5.0;
interface IBancorFinder {
function buildBancorPath(
IERC20 fromToken,
IERC20 destToken
)
external
view
returns(address[] memory path);
}
// File: contracts/interface/IOasisExchange.sol
pragma solidity ^0.5.0;
interface IOasisExchange {
function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt)
external
view
returns (uint256 fillAmt);
function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount)
external
returns (uint256 fillAmt);
}
// File: contracts/interface/IWETH.sol
pragma solidity ^0.5.0;
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/ICurve.sol
pragma solidity ^0.5.0;
interface ICurve {
// solium-disable-next-line mixedcase
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function get_dy(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external;
// solium-disable-next-line mixedcase
function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external;
}
contract ICurveRegistry {
function get_pool_info(address pool)
external
view
returns(
uint256[8] memory balances,
uint256[8] memory underlying_balances,
uint256[8] memory decimals,
uint256[8] memory underlying_decimals,
address lp_token,
uint256 A,
uint256 fee
);
}
contract ICurveCalculator {
function get_dy(
int128 nCoins,
uint256[8] calldata balances,
uint256 amp,
uint256 fee,
uint256[8] calldata rates,
uint256[8] calldata precisions,
bool underlying,
int128 i,
int128 j,
uint256[100] calldata dx
) external view returns(uint256[100] memory dy);
}
// File: contracts/interface/IChai.sol
pragma solidity ^0.5.0;
interface IPot {
function dsr() external view returns (uint256);
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
contract IChai is IERC20 {
function POT() public view returns (IPot);
function join(address dst, uint256 wad) external;
function exit(address src, uint256 wad) external;
}
library ChaiHelper {
IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
uint256 private constant RAY = 10**27;
function _mul(uint256 x, uint256 y) private pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, y) / RAY;
}
function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, RAY) / y;
}
function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) {
// solium-disable-next-line security/no-inline-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
function potDrip() private view returns (uint256) {
return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi());
}
function chaiPrice(IChai chai) internal view returns(uint256) {
return chaiToDai(chai, 1e18);
}
function daiToChai(
IChai /*chai*/,
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rdiv(amount, chi);
}
function chaiToDai(
IChai /*chai*/,
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rmul(chi, amount);
}
}
// File: contracts/interface/ICompound.sol
pragma solidity ^0.5.0;
contract ICompound {
function markets(address cToken)
external
view
returns (bool isListed, uint256 collateralFactorMantissa);
}
contract ICompoundToken is IERC20 {
function underlying() external view returns (address);
function exchangeRateStored() external view returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
}
contract ICompoundEther is IERC20 {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
}
// File: contracts/interface/ICompoundRegistry.sol
pragma solidity ^0.5.0;
contract ICompoundRegistry {
function tokenByCToken(ICompoundToken cToken) external view returns(IERC20);
function cTokenByToken(IERC20 token) external view returns(ICompoundToken);
}
// File: contracts/interface/IAaveToken.sol
pragma solidity ^0.5.0;
contract IAaveToken is IERC20 {
function underlyingAssetAddress() external view returns (IERC20);
function redeem(uint256 amount) external;
}
interface IAaveLendingPool {
function core() external view returns (address);
function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
}
// File: contracts/interface/IAaveRegistry.sol
pragma solidity ^0.5.0;
contract IAaveRegistry {
function tokenByAToken(IAaveToken aToken) external view returns(IERC20);
function aTokenByToken(IERC20 token) external view returns(IAaveToken);
}
// File: contracts/interface/IMooniswap.sol
pragma solidity ^0.5.0;
interface IMooniswapRegistry {
function pools(IERC20 token1, IERC20 token2) external view returns(IMooniswap);
function isPool(address addr) external view returns(bool);
}
interface IMooniswap {
function fee() external view returns (uint256);
function tokens(uint256 i) external view returns (IERC20);
function deposit(uint256[] calldata amounts, uint256[] calldata minAmounts) external payable returns(uint256 fairSupply);
function withdraw(uint256 amount, uint256[] calldata minReturns) external;
function getBalanceForAddition(IERC20 token) external view returns(uint256);
function getBalanceForRemoval(IERC20 token) external view returns(uint256);
function getReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
)
external
view
returns(uint256 returnAmount);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
address referral
)
external
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
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 Returns the average of two numbers. The result is rounded towards
* zero.
*/
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: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/UniversalERC20.sol
pragma solidity ^0.5.0;
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount == 0) {
token.safeApprove(to, 0);
return;
}
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
function eq(IERC20 a, IERC20 b) internal pure returns(bool) {
return a == b || (isETH(a) && isETH(b));
}
function notExist(IERC20 token) internal pure returns(bool) {
return (address(token) == address(-1));
}
}
// File: contracts/interface/IUniswapV2Exchange.sol
pragma solidity ^0.5.0;
interface IUniswapV2Exchange {
function getReserves() external view returns(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
}
library UniswapV2ExchangeLib {
using Math for uint256;
using SafeMath for uint256;
using UniversalERC20 for IERC20;
function getReturn(
IUniswapV2Exchange exchange,
IERC20 fromToken,
IERC20 destToken,
uint amountIn
) internal view returns (uint256 result, bool needSync, bool needSkim) {
uint256 reserveIn = fromToken.universalBalanceOf(address(exchange));
uint256 reserveOut = destToken.universalBalanceOf(address(exchange));
(uint112 reserve0, uint112 reserve1,) = exchange.getReserves();
if (fromToken > destToken) {
(reserve0, reserve1) = (reserve1, reserve0);
}
needSync = (reserveIn < reserve0 || reserveOut < reserve1);
needSkim = !needSync && (reserveIn > reserve0 || reserveOut > reserve1);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(Math.min(reserveOut, reserve1));
uint256 denominator = Math.min(reserveIn, reserve0).mul(1000).add(amountInWithFee);
result = (denominator == 0) ? 0 : numerator.div(denominator);
}
}
// File: contracts/interface/IUniswapV2Factory.sol
pragma solidity ^0.5.0;
interface IUniswapV2Factory {
function getPair(IERC20 tokenA, IERC20 tokenB) external view returns (IUniswapV2Exchange pair);
}
// File: contracts/interface/IDForceSwap.sol
pragma solidity ^0.5.0;
interface IDForceSwap {
function getAmountByInput(IERC20 input, IERC20 output, uint256 amount) external view returns(uint256);
function swap(IERC20 input, IERC20 output, uint256 amount) external;
}
// File: contracts/interface/IShell.sol
pragma solidity ^0.5.0;
interface IShell {
function viewOriginTrade(
address origin,
address target,
uint256 originAmount
) external view returns (uint256);
function swapByOrigin(
address origin,
address target,
uint256 originAmount,
uint256 minTargetAmount,
uint256 deadline
) external returns (uint256);
}
// File: contracts/interface/IMStable.sol
pragma solidity ^0.5.0;
contract IMStable is IERC20 {
function getSwapOutput(
IERC20 _input,
IERC20 _output,
uint256 _quantity
)
external
view
returns (bool, string memory, uint256 output);
function swap(
IERC20 _input,
IERC20 _output,
uint256 _quantity,
address _recipient
)
external
returns (uint256 output);
function redeem(
IERC20 _basset,
uint256 _bassetQuantity
)
external
returns (uint256 massetRedeemed);
}
interface IMassetValidationHelper {
/**
* @dev Returns a valid bAsset to redeem
* @param _mAsset Masset addr
* @return valid bool
* @return string message
* @return address of bAsset to redeem
*/
function suggestRedeemAsset(
IERC20 _mAsset
)
external
view
returns (
bool valid,
string memory err,
address token
);
/**
* @dev Returns a valid bAsset with which to mint
* @param _mAsset Masset addr
* @return valid bool
* @return string message
* @return address of bAsset to mint
*/
function suggestMintAsset(
IERC20 _mAsset
)
external
view
returns (
bool valid,
string memory err,
address token
);
/**
* @dev Determines if a given Redemption is valid
* @param _mAsset Address of the given mAsset (e.g. mUSD)
* @param _mAssetQuantity Amount of mAsset to redeem (in mUSD units)
* @param _outputBasset Desired output bAsset
* @return valid
* @return validity reason
* @return output in bAsset units
* @return bAssetQuantityArg - required input argument to the 'redeem' call
*/
function getRedeemValidity(
IERC20 _mAsset,
uint256 _mAssetQuantity,
IERC20 _outputBasset
)
external
view
returns (
bool valid,
string memory,
uint256 output,
uint256 bassetQuantityArg
);
}
// File: contracts/interface/IBalancerPool.sol
pragma solidity ^0.5.0;
interface IBalancerPool {
function getSwapFee()
external view returns (uint256 balance);
function getDenormalizedWeight(IERC20 token)
external view returns (uint256 balance);
function getBalance(IERC20 token)
external view returns (uint256 balance);
function swapExactAmountIn(
IERC20 tokenIn,
uint256 tokenAmountIn,
IERC20 tokenOut,
uint256 minAmountOut,
uint256 maxPrice
)
external
returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
}
// 0xA961672E8Db773be387e775bc4937C678F3ddF9a
interface IBalancerHelper {
function getReturns(
IBalancerPool pool,
IERC20 fromToken,
IERC20 destToken,
uint256[] calldata amounts
)
external
view
returns(uint256[] memory rets);
}
// File: contracts/interface/IBalancerRegistry.sol
pragma solidity ^0.5.0;
interface IBalancerRegistry {
event PoolAdded(
address indexed pool
);
event PoolTokenPairAdded(
address indexed pool,
address indexed fromToken,
address indexed destToken
);
event IndicesUpdated(
address indexed fromToken,
address indexed destToken,
bytes32 oldIndices,
bytes32 newIndices
);
// Get info about pool pair for 1 SLOAD
function getPairInfo(address pool, address fromToken, address destToken)
external view returns(uint256 weight1, uint256 weight2, uint256 swapFee);
// Pools
function checkAddedPools(address pool)
external view returns(bool);
function getAddedPoolsLength()
external view returns(uint256);
function getAddedPools()
external view returns(address[] memory);
function getAddedPoolsWithLimit(uint256 offset, uint256 limit)
external view returns(address[] memory result);
// Tokens
function getAllTokensLength()
external view returns(uint256);
function getAllTokens()
external view returns(address[] memory);
function getAllTokensWithLimit(uint256 offset, uint256 limit)
external view returns(address[] memory result);
// Pairs
function getPoolsLength(address fromToken, address destToken)
external view returns(uint256);
function getPools(address fromToken, address destToken)
external view returns(address[] memory);
function getPoolsWithLimit(address fromToken, address destToken, uint256 offset, uint256 limit)
external view returns(address[] memory result);
function getBestPools(address fromToken, address destToken)
external view returns(address[] memory pools);
function getBestPoolsWithLimit(address fromToken, address destToken, uint256 limit)
external view returns(address[] memory pools);
// Get swap rates
function getPoolReturn(address pool, address fromToken, address destToken, uint256 amount)
external view returns(uint256);
function getPoolReturns(address pool, address fromToken, address destToken, uint256[] calldata amounts)
external view returns(uint256[] memory result);
// Add and update registry
function addPool(address pool) external returns(uint256 listed);
function addPools(address[] calldata pools) external returns(uint256[] memory listed);
function updatedIndices(address[] calldata tokens, uint256 lengthLimit) external;
}
// File: contracts/BalancerLib.sol
pragma solidity ^0.5.0;
library BalancerLib {
uint public constant BONE = 10**18;
uint public constant MIN_BOUND_TOKENS = 2;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant MIN_FEE = BONE / 10**6;
uint public constant MAX_FEE = BONE / 10;
uint public constant EXIT_FEE = 0;
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**12;
uint public constant INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
function btoi(uint a)
internal pure
returns (uint)
{
return a / BONE;
}
function bfloor(uint a)
internal pure
returns (uint)
{
return btoi(a) * BONE;
}
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint a, uint n)
internal pure
returns (uint)
{
uint z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint base, uint exp)
internal pure
returns (uint)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint whole = bfloor(exp);
uint remain = bsub(exp, whole);
uint wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
// term 0:
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
)
internal pure
returns (uint spotPrice)
{
uint numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint ratio = bdiv(numer, denom);
uint scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
)
internal pure
returns (uint tokenAmountOut)
{
uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
if (y == 0) {
return 0;
}
uint foo = bpow(y, weightRatio);
uint bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
)
internal pure
returns (uint tokenAmountIn)
{
uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint diff = bsub(tokenBalanceOut, tokenAmountOut);
uint y = bdiv(tokenBalanceOut, diff);
if (y == 0) {
return 0;
}
uint foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
)
internal pure
returns (uint poolAmountOut)
{
// Charge the trading fee for the proportion of tokenAi
/// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint poolRatio = bpow(tokenInRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
internal pure
returns (uint tokenAmountIn)
{
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint newPoolSupply = badd(poolSupply, poolAmountOut);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint boo = bdiv(BONE, normalizedWeight);
uint tokenInRatio = bpow(poolRatio, boo);
uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
)
internal pure
returns (uint tokenAmountOut)
{
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE));
uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
)
internal pure
returns (uint poolAmountIn)
{
// charge swap fee on the output token side
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint zoo = bsub(BONE, normalizedWeight);
uint zar = bmul(zoo, swapFee);
uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));
return poolAmountIn;
}
}
// File: contracts/OneSplitBase.sol
pragma solidity ^0.5.0;
contract IOneSplitView is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
}
library DisableFlags {
function check(uint256 flags, uint256 flag) internal pure returns(bool) {
return (flags & flag) != 0;
}
}
contract OneSplitRoot is IOneSplitView {
using SafeMath for uint256;
using DisableFlags for uint256;
using UniversalERC20 for IERC20;
using UniversalERC20 for IWETH;
using UniswapV2ExchangeLib for IUniswapV2Exchange;
using ChaiHelper for IChai;
uint256 constant internal DEXES_COUNT = 34;
IERC20 constant internal ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 constant internal ZERO_ADDRESS = IERC20(0);
IBancorEtherToken constant internal bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IChai constant internal chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
IERC20 constant internal dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 constant internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 constant internal usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 constant internal tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
IERC20 constant internal busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
IERC20 constant internal susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
IERC20 constant internal pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1);
IERC20 constant internal renbtc = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D);
IERC20 constant internal wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IERC20 constant internal tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847);
IERC20 constant internal hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380);
IERC20 constant internal sbtc = IERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6);
IKyberNetworkProxy constant internal kyberNetworkProxy = IKyberNetworkProxy(0x9AAb3f75489902f3a48495025729a0AF77d4b11e);
IKyberStorage constant internal kyberStorage = IKyberStorage(0xC8fb12402cB16970F3C5F4b48Ff68Eb9D1289301);
IKyberHintHandler constant internal kyberHintHandler = IKyberHintHandler(0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C);
IUniswapFactory constant internal uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
IBancorContractRegistry constant internal bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4);
IBancorNetworkPathFinder constant internal bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
//IBancorConverterRegistry constant internal bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518);
IBancorFinder constant internal bancorFinder = IBancorFinder(0x2B344e14dc2641D11D338C053C908c7A7D4c30B9);
IOasisExchange constant internal oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D);
ICurve constant internal curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56);
ICurve constant internal curveUSDT = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C);
ICurve constant internal curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
ICurve constant internal curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27);
ICurve constant internal curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD);
ICurve constant internal curvePAX = ICurve(0x06364f10B501e868329afBc005b3492902d6C763);
ICurve constant internal curveRenBTC = ICurve(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
ICurve constant internal curveTBTC = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E);
ICurve constant internal curveSBTC = ICurve(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714);
IShell constant internal shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D);
IAaveLendingPool constant internal aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
ICompound constant internal compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ICompoundEther constant internal cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
IMooniswapRegistry constant internal mooniswapRegistry = IMooniswapRegistry(0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303);
IUniswapV2Factory constant internal uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
IDForceSwap constant internal dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2);
IMStable constant internal musd = IMStable(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
IMassetValidationHelper constant internal musd_helper = IMassetValidationHelper(0xaBcC93c3be238884cc3309C19Afd128fAfC16911);
IBalancerRegistry constant internal balancerRegistry = IBalancerRegistry(0x65e67cbc342712DF67494ACEfc06fe951EE93982);
ICurveCalculator constant internal curveCalculator = ICurveCalculator(0xc1DB00a8E5Ef7bfa476395cdbcc98235477cDE4E);
ICurveRegistry constant internal curveRegistry = ICurveRegistry(0x7002B727Ef8F5571Cb5F9D70D13DBEEb4dFAe9d1);
ICompoundRegistry constant internal compoundRegistry = ICompoundRegistry(0xF451Dbd7Ba14BFa7B1B78A766D3Ed438F79EE1D1);
IAaveRegistry constant internal aaveRegistry = IAaveRegistry(0xEd8b133B7B88366E01Bb9E38305Ab11c26521494);
IBalancerHelper constant internal balancerHelper = IBalancerHelper(0xA961672E8Db773be387e775bc4937C678F3ddF9a);
int256 internal constant VERY_NEGATIVE_VALUE = -1e72;
function _findBestDistribution(
uint256 s, // parts
int256[][] memory amounts // exchangesReturns
)
internal
pure
returns(
int256 returnAmount,
uint256[] memory distribution
)
{
uint256 n = amounts.length;
int256[][] memory answer = new int256[][](n); // int[n][s+1]
uint256[][] memory parent = new uint256[][](n); // int[n][s+1]
for (uint i = 0; i < n; i++) {
answer[i] = new int256[](s + 1);
parent[i] = new uint256[](s + 1);
}
for (uint j = 0; j <= s; j++) {
answer[0][j] = amounts[0][j];
for (uint i = 1; i < n; i++) {
answer[i][j] = -1e72;
}
parent[0][j] = 0;
}
for (uint i = 1; i < n; i++) {
for (uint j = 0; j <= s; j++) {
answer[i][j] = answer[i - 1][j];
parent[i][j] = j;
for (uint k = 1; k <= j; k++) {
if (answer[i - 1][j - k] + amounts[i][k] > answer[i][j]) {
answer[i][j] = answer[i - 1][j - k] + amounts[i][k];
parent[i][j] = j - k;
}
}
}
}
distribution = new uint256[](DEXES_COUNT);
uint256 partsLeft = s;
for (uint curExchange = n - 1; partsLeft > 0; curExchange--) {
distribution[curExchange] = partsLeft - parent[curExchange][partsLeft];
partsLeft = parent[curExchange][partsLeft];
}
returnAmount = (answer[n - 1][s] == VERY_NEGATIVE_VALUE) ? 0 : answer[n - 1][s];
}
function _kyberReserveIdByTokens(
IERC20 fromToken,
IERC20 destToken
) internal view returns(bytes32) {
if (!fromToken.isETH() && !destToken.isETH()) {
return 0;
}
bytes32[] memory reserveIds = kyberStorage.getReserveIdsPerTokenSrc(
fromToken.isETH() ? destToken : fromToken
);
for (uint i = 0; i < reserveIds.length; i++) {
if ((uint256(reserveIds[i]) >> 248) != 0xBB && // Bridge
reserveIds[i] != 0xff4b796265722046707200000000000000000000000000000000000000000000 && // Reserve 1
reserveIds[i] != 0xffabcd0000000000000000000000000000000000000000000000000000000000 && // Reserve 2
reserveIds[i] != 0xff4f6e65426974205175616e7400000000000000000000000000000000000000) // Reserve 3
{
return reserveIds[i];
}
}
return 0;
}
function _scaleDestTokenEthPriceTimesGasPrice(
IERC20 fromToken,
IERC20 destToken,
uint256 destTokenEthPriceTimesGasPrice
) internal view returns(uint256) {
if (fromToken == destToken) {
return destTokenEthPriceTimesGasPrice;
}
uint256 mul = _cheapGetPrice(ETH_ADDRESS, destToken, 0.01 ether);
uint256 div = _cheapGetPrice(ETH_ADDRESS, fromToken, 0.01 ether);
if (div > 0) {
return destTokenEthPriceTimesGasPrice.mul(mul).div(div);
}
return 0;
}
function _cheapGetPrice(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal view returns(uint256 returnAmount) {
(returnAmount,,) = this.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
1,
FLAG_DISABLE_SPLIT_RECALCULATION |
FLAG_DISABLE_ALL_SPLIT_SOURCES |
FLAG_DISABLE_UNISWAP_V2_ALL |
FLAG_DISABLE_UNISWAP,
0
);
}
function _linearInterpolation(
uint256 value,
uint256 parts
) internal pure returns(uint256[] memory rets) {
rets = new uint256[](parts);
for (uint i = 0; i < parts; i++) {
rets[i] = value.mul(i + 1).div(parts);
}
}
function _tokensEqual(IERC20 tokenA, IERC20 tokenB) internal pure returns(bool) {
return ((tokenA.isETH() && tokenB.isETH()) || tokenA == tokenB);
}
}
contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = this.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _getExpectedReturnRespectingGasFloor(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnRespectingGasFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
}
contract OneSplitView is IOneSplitView, OneSplitRoot {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
if (fromToken == destToken) {
return (amount, 0, distribution);
}
function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory reserves = _getAllReserves(flags);
int256[][] memory matrix = new int256[][](DEXES_COUNT);
uint256[DEXES_COUNT] memory gases;
bool atLeastOnePositive = false;
for (uint i = 0; i < DEXES_COUNT; i++) {
uint256[] memory rets;
(rets, gases[i]) = reserves[i](fromToken, destToken, amount, parts, flags);
// Prepend zero and sub gas
int256 gas = int256(gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18));
matrix[i] = new int256[](parts + 1);
for (uint j = 0; j < rets.length; j++) {
matrix[i][j + 1] = int256(rets[j]) - gas;
atLeastOnePositive = atLeastOnePositive || (matrix[i][j + 1] > 0);
}
}
if (!atLeastOnePositive) {
for (uint i = 0; i < DEXES_COUNT; i++) {
for (uint j = 1; j < parts + 1; j++) {
if (matrix[i][j] == 0) {
matrix[i][j] = VERY_NEGATIVE_VALUE;
}
}
}
}
(, distribution) = _findBestDistribution(parts, matrix);
(returnAmount, estimateGasAmount) = _getReturnAndGasByDistribution(
Args({
fromToken: fromToken,
destToken: destToken,
amount: amount,
parts: parts,
flags: flags,
destTokenEthPriceTimesGasPrice: destTokenEthPriceTimesGasPrice,
distribution: distribution,
matrix: matrix,
gases: gases,
reserves: reserves
})
);
return (returnAmount, estimateGasAmount, distribution);
}
struct Args {
IERC20 fromToken;
IERC20 destToken;
uint256 amount;
uint256 parts;
uint256 flags;
uint256 destTokenEthPriceTimesGasPrice;
uint256[] distribution;
int256[][] matrix;
uint256[DEXES_COUNT] gases;
function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] reserves;
}
function _getReturnAndGasByDistribution(
Args memory args
) internal view returns(uint256 returnAmount, uint256 estimateGasAmount) {
bool[DEXES_COUNT] memory exact = [
true, // "Uniswap",
false, // "Kyber",
false, // "Bancor",
false, // "Oasis",
true, // "Curve Compound",
true, // "Curve USDT",
true, // "Curve Y",
true, // "Curve Binance",
true, // "Curve Synthetix",
true, // "Uniswap Compound",
true, // "Uniswap CHAI",
true, // "Uniswap Aave",
true, // "Mooniswap 1",
true, // "Uniswap V2",
true, // "Uniswap V2 (ETH)",
true, // "Uniswap V2 (DAI)",
true, // "Uniswap V2 (USDC)",
true, // "Curve Pax",
true, // "Curve RenBTC",
true, // "Curve tBTC",
true, // "Dforce XSwap",
false, // "Shell",
true, // "mStable",
true, // "Curve sBTC"
true, // "Balancer 1"
true, // "Balancer 2"
true, // "Balancer 3"
true, // "Kyber 1"
true, // "Kyber 2"
true, // "Kyber 3"
true, // "Kyber 4"
true, // "Mooniswap 2"
true, // "Mooniswap 3"
true // "Mooniswap 4"
];
for (uint i = 0; i < DEXES_COUNT; i++) {
if (args.distribution[i] > 0) {
if (args.distribution[i] == args.parts || exact[i] || args.flags.check(FLAG_DISABLE_SPLIT_RECALCULATION)) {
estimateGasAmount = estimateGasAmount.add(args.gases[i]);
int256 value = args.matrix[i][args.distribution[i]];
returnAmount = returnAmount.add(uint256(
(value == VERY_NEGATIVE_VALUE ? 0 : value) +
int256(args.gases[i].mul(args.destTokenEthPriceTimesGasPrice).div(1e18))
));
}
else {
(uint256[] memory rets, uint256 gas) = args.reserves[i](args.fromToken, args.destToken, args.amount.mul(args.distribution[i]).div(args.parts), 1, args.flags);
estimateGasAmount = estimateGasAmount.add(gas);
returnAmount = returnAmount.add(rets[0]);
}
}
}
}
function _getAllReserves(uint256 flags)
internal
pure
returns(function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory)
{
bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES);
return [
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP) ? _calculateNoReturn : calculateUniswap,
_calculateNoReturn, // invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyber,
invert != flags.check(FLAG_DISABLE_BANCOR) ? _calculateNoReturn : calculateBancor,
invert != flags.check(FLAG_DISABLE_OASIS) ? _calculateNoReturn : calculateOasis,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_COMPOUND) ? _calculateNoReturn : calculateCurveCompound,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_USDT) ? _calculateNoReturn : calculateCurveUSDT,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_Y) ? _calculateNoReturn : calculateCurveY,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_BINANCE) ? _calculateNoReturn : calculateCurveBinance,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SYNTHETIX) ? _calculateNoReturn : calculateCurveSynthetix,
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_COMPOUND) ? _calculateNoReturn : calculateUniswapCompound,
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_CHAI) ? _calculateNoReturn : calculateUniswapChai,
invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_AAVE) ? _calculateNoReturn : calculateUniswapAave,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP) ? _calculateNoReturn : calculateMooniswap,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2) ? _calculateNoReturn : calculateUniswapV2,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_ETH) ? _calculateNoReturn : calculateUniswapV2ETH,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_DAI) ? _calculateNoReturn : calculateUniswapV2DAI,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_PAX) ? _calculateNoReturn : calculateCurvePAX,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_RENBTC) ? _calculateNoReturn : calculateCurveRenBTC,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_TBTC) ? _calculateNoReturn : calculateCurveTBTC,
invert != flags.check(FLAG_DISABLE_DFORCE_SWAP) ? _calculateNoReturn : calculateDforceSwap,
invert != flags.check(FLAG_DISABLE_SHELL) ? _calculateNoReturn : calculateShell,
invert != flags.check(FLAG_DISABLE_MSTABLE_MUSD) ? _calculateNoReturn : calculateMStableMUSD,
invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SBTC) ? _calculateNoReturn : calculateCurveSBTC,
invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_1) ? _calculateNoReturn : calculateBalancer1,
invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_2) ? _calculateNoReturn : calculateBalancer2,
invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_3) ? _calculateNoReturn : calculateBalancer3,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_1) ? _calculateNoReturn : calculateKyber1,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_2) ? _calculateNoReturn : calculateKyber2,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_3) ? _calculateNoReturn : calculateKyber3,
invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_4) ? _calculateNoReturn : calculateKyber4,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP_ETH) ? _calculateNoReturn : calculateMooniswapOverETH,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP_DAI) ? _calculateNoReturn : calculateMooniswapOverDAI,
invert != flags.check(FLAG_DISABLE_MOONISWAP_ALL | FLAG_DISABLE_MOONISWAP_USDC) ? _calculateNoReturn : calculateMooniswapOverUSDC
];
}
function _calculateNoGas(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 /*parts*/,
uint256 /*destTokenEthPriceTimesGasPrice*/,
uint256 /*flags*/,
uint256 /*destTokenEthPrice*/
) internal view returns(uint256[] memory /*rets*/, uint256 /*gas*/) {
this;
}
// View Helpers
struct Balances {
uint256 src;
uint256 dst;
}
function _calculateBalancer(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 poolIndex
) internal view returns(uint256[] memory rets, uint256 gas) {
address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
address(fromToken.isETH() ? weth : fromToken),
address(destToken.isETH() ? weth : destToken),
poolIndex + 1
);
if (poolIndex >= pools.length) {
return (new uint256[](parts), 0);
}
rets = balancerHelper.getReturns(
IBalancerPool(pools[poolIndex]),
fromToken.isETH() ? weth : fromToken,
destToken.isETH() ? weth : destToken,
_linearInterpolation(amount, parts)
);
gas = 75_000 + (fromToken.isETH() || destToken.isETH() ? 0 : 65_000);
}
function calculateBalancer1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateBalancer(
fromToken,
destToken,
amount,
parts,
0
);
}
function calculateBalancer2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateBalancer(
fromToken,
destToken,
amount,
parts,
1
);
}
function calculateBalancer3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateBalancer(
fromToken,
destToken,
amount,
parts,
2
);
}
function calculateMStableMUSD(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](parts);
if ((fromToken != usdc && fromToken != dai && fromToken != usdt && fromToken != tusd) ||
(destToken != usdc && destToken != dai && destToken != usdt && destToken != tusd))
{
return (rets, 0);
}
for (uint i = 1; i <= parts; i *= 2) {
(bool success, bytes memory data) = address(musd).staticcall(abi.encodeWithSelector(
musd.getSwapOutput.selector,
fromToken,
destToken,
amount.mul(parts.div(i)).div(parts)
));
if (success && data.length > 0) {
(,, uint256 maxRet) = abi.decode(data, (bool,string,uint256));
if (maxRet > 0) {
for (uint j = 0; j < parts.div(i); j++) {
rets[j] = maxRet.mul(j + 1).div(parts.div(i));
}
break;
}
}
}
return (
rets,
700_000
);
}
function _getCurvePoolInfo(
ICurve curve,
bool haveUnderlying
) internal view returns(
uint256[8] memory balances,
uint256[8] memory precisions,
uint256[8] memory rates,
uint256 amp,
uint256 fee
) {
uint256[8] memory underlying_balances;
uint256[8] memory decimals;
uint256[8] memory underlying_decimals;
(
balances,
underlying_balances,
decimals,
underlying_decimals,
/*address lp_token*/,
amp,
fee
) = curveRegistry.get_pool_info(address(curve));
for (uint k = 0; k < 8 && balances[k] > 0; k++) {
precisions[k] = 10 ** (18 - (haveUnderlying ? underlying_decimals : decimals)[k]);
if (haveUnderlying) {
rates[k] = underlying_balances[k].mul(1e18).div(balances[k]);
} else {
rates[k] = 1e18;
}
}
}
function _calculateCurveSelector(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
ICurve curve,
bool haveUnderlying,
IERC20[] memory tokens
) internal view returns(uint256[] memory rets) {
rets = new uint256[](parts);
int128 i = 0;
int128 j = 0;
for (uint t = 0; t < tokens.length; t++) {
if (fromToken == tokens[t]) {
i = int128(t + 1);
}
if (destToken == tokens[t]) {
j = int128(t + 1);
}
}
if (i == 0 || j == 0) {
return rets;
}
bytes memory data = abi.encodePacked(
uint256(haveUnderlying ? 1 : 0),
uint256(i - 1),
uint256(j - 1),
_linearInterpolation100(amount, parts)
);
(
uint256[8] memory balances,
uint256[8] memory precisions,
uint256[8] memory rates,
uint256 amp,
uint256 fee
) = _getCurvePoolInfo(curve, haveUnderlying);
bool success;
(success, data) = address(curveCalculator).staticcall(
abi.encodePacked(
abi.encodeWithSelector(
curveCalculator.get_dy.selector,
tokens.length,
balances,
amp,
fee,
rates,
precisions
),
data
)
);
if (!success || data.length == 0) {
return rets;
}
uint256[100] memory dy = abi.decode(data, (uint256[100]));
for (uint t = 0; t < parts; t++) {
rets[t] = dy[t];
}
}
function _linearInterpolation100(
uint256 value,
uint256 parts
) internal pure returns(uint256[100] memory rets) {
for (uint i = 0; i < parts; i++) {
rets[i] = value.mul(i + 1).div(parts);
}
}
function calculateCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = dai;
tokens[1] = usdc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveCompound,
true,
tokens
), 720_000);
}
function calculateCurveUSDT(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveUSDT,
true,
tokens
), 720_000);
}
function calculateCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = tusd;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveY,
true,
tokens
), 1_400_000);
}
function calculateCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = busd;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveBinance,
true,
tokens
), 1_400_000);
}
function calculateCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = susd;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveSynthetix,
true,
tokens
), 200_000);
}
function calculateCurvePAX(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = pax;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curvePAX,
true,
tokens
), 1_000_000);
}
function calculateCurveRenBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = renbtc;
tokens[1] = wbtc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveRenBTC,
false,
tokens
), 130_000);
}
function calculateCurveTBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = tbtc;
tokens[1] = wbtc;
tokens[2] = hbtc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveTBTC,
false,
tokens
), 145_000);
}
function calculateCurveSBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = renbtc;
tokens[1] = wbtc;
tokens[2] = sbtc;
return (_calculateCurveSelector(
fromToken,
destToken,
amount,
parts,
curveSBTC,
false,
tokens
), 150_000);
}
function calculateShell(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
(bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector(
shell.viewOriginTrade.selector,
fromToken,
destToken,
amount
));
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
return (_linearInterpolation(maxRet, parts), 300_000);
}
function calculateDforceSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
(bool success, bytes memory data) = address(dforceSwap).staticcall(
abi.encodeWithSelector(
dforceSwap.getAmountByInput.selector,
fromToken,
destToken,
amount
)
);
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
uint256 available = destToken.universalBalanceOf(address(dforceSwap));
if (maxRet > available) {
return (new uint256[](parts), 0);
}
return (_linearInterpolation(maxRet, parts), 160_000);
}
function _calculateUniswapFormula(uint256 fromBalance, uint256 toBalance, uint256 amount) internal pure returns(uint256) {
if (amount == 0) {
return 0;
}
return amount.mul(toBalance).mul(997).div(
fromBalance.mul(1000).add(amount.mul(997))
);
}
function _calculateUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = amounts;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange == IUniswapExchange(0)) {
return (new uint256[](rets.length), 0);
}
uint256 fromTokenBalance = fromToken.universalBalanceOf(address(fromExchange));
uint256 fromEtherBalance = address(fromExchange).balance;
for (uint i = 0; i < rets.length; i++) {
rets[i] = _calculateUniswapFormula(fromTokenBalance, fromEtherBalance, rets[i]);
}
}
if (!destToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
if (toExchange == IUniswapExchange(0)) {
return (new uint256[](rets.length), 0);
}
uint256 toEtherBalance = address(toExchange).balance;
uint256 toTokenBalance = destToken.universalBalanceOf(address(toExchange));
for (uint i = 0; i < rets.length; i++) {
rets[i] = _calculateUniswapFormula(toEtherBalance, toTokenBalance, rets[i]);
}
}
return (rets, fromToken.isETH() || destToken.isETH() ? 60_000 : 100_000);
}
function calculateUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateUniswap(
fromToken,
destToken,
_linearInterpolation(amount, parts),
flags
);
}
function _calculateUniswapWrapped(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 midTokenPrice,
uint256 flags,
uint256 gas1,
uint256 gas2
) internal view returns(uint256[] memory rets, uint256 gas) {
if (!fromToken.isETH() && destToken.isETH()) {
(rets, gas) = _calculateUniswap(
midToken,
destToken,
_linearInterpolation(amount.mul(1e18).div(midTokenPrice), parts),
flags
);
return (rets, gas + gas1);
}
else if (fromToken.isETH() && !destToken.isETH()) {
(rets, gas) = _calculateUniswap(
fromToken,
midToken,
_linearInterpolation(amount, parts),
flags
);
for (uint i = 0; i < parts; i++) {
rets[i] = rets[i].mul(midTokenPrice).div(1e18);
}
return (rets, gas + gas2);
}
return (new uint256[](parts), 0);
}
function calculateUniswapCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20 midPreToken;
if (!fromToken.isETH() && destToken.isETH()) {
midPreToken = fromToken;
}
else if (!destToken.isETH() && fromToken.isETH()) {
midPreToken = destToken;
}
if (!midPreToken.isETH()) {
ICompoundToken midToken = compoundRegistry.cTokenByToken(midPreToken);
if (midToken != ICompoundToken(0)) {
return _calculateUniswapWrapped(
fromToken,
midToken,
destToken,
amount,
parts,
midToken.exchangeRateStored(),
flags,
200_000,
200_000
);
}
}
return (new uint256[](parts), 0);
}
function calculateUniswapChai(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai && destToken.isETH() ||
fromToken.isETH() && destToken == dai)
{
return _calculateUniswapWrapped(
fromToken,
chai,
destToken,
amount,
parts,
chai.chaiPrice(),
flags,
180_000,
160_000
);
}
return (new uint256[](parts), 0);
}
function calculateUniswapAave(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20 midPreToken;
if (!fromToken.isETH() && destToken.isETH()) {
midPreToken = fromToken;
}
else if (!destToken.isETH() && fromToken.isETH()) {
midPreToken = destToken;
}
if (!midPreToken.isETH()) {
IAaveToken midToken = aaveRegistry.aTokenByToken(midPreToken);
if (midToken != IAaveToken(0)) {
return _calculateUniswapWrapped(
fromToken,
midToken,
destToken,
amount,
parts,
1e18,
flags,
310_000,
670_000
);
}
}
return (new uint256[](parts), 0);
}
function calculateKyber1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
0xff4b796265722046707200000000000000000000000000000000000000000000 // 0x63825c174ab367968EC60f061753D3bbD36A0D8F
);
}
function calculateKyber2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
0xffabcd0000000000000000000000000000000000000000000000000000000000 // 0x7a3370075a54B187d7bD5DceBf0ff2B5552d4F7D
);
}
function calculateKyber3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
0xff4f6e65426974205175616e7400000000000000000000000000000000000000 // 0x4f32BbE8dFc9efD54345Fc936f9fEF1048746fCF
);
}
function calculateKyber4(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
bytes32 reserveId = _kyberReserveIdByTokens(fromToken, destToken);
if (reserveId == 0) {
return (new uint256[](parts), 0);
}
return _calculateKyber(
fromToken,
destToken,
amount,
parts,
flags,
reserveId
);
}
function _kyberGetRate(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags,
bytes memory hint
) private view returns(uint256) {
(, bytes memory data) = address(kyberNetworkProxy).staticcall(
abi.encodeWithSelector(
kyberNetworkProxy.getExpectedRateAfterFee.selector,
fromToken,
destToken,
amount,
(flags >> 255) * 10,
hint
)
);
return (data.length == 32) ? abi.decode(data, (uint256)) : 0;
}
function _calculateKyber(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
bytes32 reserveId
) internal view returns(uint256[] memory rets, uint256 gas) {
bytes memory fromHint;
bytes memory destHint;
{
bytes32[] memory reserveIds = new bytes32[](1);
reserveIds[0] = reserveId;
(bool success, bytes memory data) = address(kyberHintHandler).staticcall(
abi.encodeWithSelector(
kyberHintHandler.buildTokenToEthHint.selector,
fromToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
)
);
fromHint = success ? abi.decode(data, (bytes)) : bytes("");
(success, data) = address(kyberHintHandler).staticcall(
abi.encodeWithSelector(
kyberHintHandler.buildEthToTokenHint.selector,
destToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
)
);
destHint = success ? abi.decode(data, (bytes)) : bytes("");
}
uint256 fromTokenDecimals = 10 ** IERC20(fromToken).universalDecimals();
uint256 destTokenDecimals = 10 ** IERC20(destToken).universalDecimals();
rets = new uint256[](parts);
for (uint i = 0; i < parts; i++) {
if (i > 0 && rets[i - 1] == 0) {
break;
}
rets[i] = amount.mul(i + 1).div(parts);
if (!fromToken.isETH()) {
if (fromHint.length == 0) {
rets[i] = 0;
break;
}
uint256 rate = _kyberGetRate(
fromToken,
ETH_ADDRESS,
rets[i],
flags,
fromHint
);
rets[i] = rate.mul(rets[i]).div(fromTokenDecimals);
}
if (!destToken.isETH() && rets[i] > 0) {
if (destHint.length == 0) {
rets[i] = 0;
break;
}
uint256 rate = _kyberGetRate(
ETH_ADDRESS,
destToken,
rets[i],
10,
destHint
);
rets[i] = rate.mul(rets[i]).mul(destTokenDecimals).div(1e36);
}
}
return (rets, 100_000);
}
function calculateBancor(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return (new uint256[](parts), 0);
// IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
// address[] memory path = bancorFinder.buildBancorPath(
// fromToken.isETH() ? bancorEtherToken : fromToken,
// destToken.isETH() ? bancorEtherToken : destToken
// );
// rets = _linearInterpolation(amount, parts);
// for (uint i = 0; i < parts; i++) {
// (bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)(
// abi.encodeWithSelector(
// bancorNetwork.getReturnByPath.selector,
// path,
// rets[i]
// )
// );
// if (!success || data.length == 0) {
// for (; i < parts; i++) {
// rets[i] = 0;
// }
// break;
// } else {
// (uint256 ret,) = abi.decode(data, (uint256,uint256));
// rets[i] = ret;
// }
// }
// return (rets, path.length.mul(150_000));
}
function calculateOasis(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = _linearInterpolation(amount, parts);
for (uint i = 0; i < parts; i++) {
(bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)(
abi.encodeWithSelector(
oasisExchange.getBuyAmount.selector,
destToken.isETH() ? weth : destToken,
fromToken.isETH() ? weth : fromToken,
rets[i]
)
);
if (!success || data.length == 0) {
for (; i < parts; i++) {
rets[i] = 0;
}
break;
} else {
rets[i] = abi.decode(data, (uint256));
}
}
return (rets, 500_000);
}
function calculateMooniswapMany(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](amounts.length);
IMooniswap mooniswap = mooniswapRegistry.pools(
fromToken.isETH() ? ZERO_ADDRESS : fromToken,
destToken.isETH() ? ZERO_ADDRESS : destToken
);
if (mooniswap == IMooniswap(0)) {
return (rets, 0);
}
uint256 fee = mooniswap.fee();
uint256 fromBalance = mooniswap.getBalanceForAddition(fromToken.isETH() ? ZERO_ADDRESS : fromToken);
uint256 destBalance = mooniswap.getBalanceForRemoval(destToken.isETH() ? ZERO_ADDRESS : destToken);
if (fromBalance == 0 || destBalance == 0) {
return (rets, 0);
}
for (uint i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i].sub(amounts[i].mul(fee).div(1e18));
rets[i] = amount.mul(destBalance).div(
fromBalance.add(amount)
);
}
return (rets, (fromToken.isETH() || destToken.isETH()) ? 80_000 : 110_000);
}
function calculateMooniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
return calculateMooniswapMany(
fromToken,
destToken,
_linearInterpolation(amount, parts)
);
}
function calculateMooniswapOverETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken.isETH() || destToken.isETH()) {
return (new uint256[](parts), 0);
}
(uint256[] memory results, uint256 gas1) = calculateMooniswap(fromToken, ZERO_ADDRESS, amount, parts, flags);
(rets, gas) = calculateMooniswapMany(ZERO_ADDRESS, destToken, results);
gas = gas.add(gas1);
}
function calculateMooniswapOverDAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai || destToken == dai) {
return (new uint256[](parts), 0);
}
(uint256[] memory results, uint256 gas1) = calculateMooniswap(fromToken, dai, amount, parts, flags);
(rets, gas) = calculateMooniswapMany(dai, destToken, results);
gas = gas.add(gas1);
}
function calculateMooniswapOverUSDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == usdc || destToken == usdc) {
return (new uint256[](parts), 0);
}
(uint256[] memory results, uint256 gas1) = calculateMooniswap(fromToken, usdc, amount, parts, flags);
(rets, gas) = calculateMooniswapMany(usdc, destToken, results);
gas = gas.add(gas1);
}
function calculateUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateUniswapV2(
fromToken,
destToken,
_linearInterpolation(amount, parts),
flags
);
}
function calculateUniswapV2ETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken.isETH() || fromToken == weth || destToken.isETH() || destToken == weth) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
weth,
destToken,
amount,
parts,
flags
);
}
function calculateUniswapV2DAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai || destToken == dai) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
dai,
destToken,
amount,
parts,
flags
);
}
function calculateUniswapV2USDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == usdc || destToken == usdc) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
usdc,
destToken,
amount,
parts,
flags
);
}
function _calculateUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](amounts.length);
IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
IERC20 destTokenReal = destToken.isETH() ? weth : destToken;
IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, destTokenReal);
if (exchange != IUniswapV2Exchange(0)) {
uint256 fromTokenBalance = fromTokenReal.universalBalanceOf(address(exchange));
uint256 destTokenBalance = destTokenReal.universalBalanceOf(address(exchange));
for (uint i = 0; i < amounts.length; i++) {
rets[i] = _calculateUniswapFormula(fromTokenBalance, destTokenBalance, amounts[i]);
}
return (rets, 50_000);
}
}
function _calculateUniswapV2OverMidToken(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = _linearInterpolation(amount, parts);
uint256 gas1;
uint256 gas2;
(rets, gas1) = _calculateUniswapV2(fromToken, midToken, rets, flags);
(rets, gas2) = _calculateUniswapV2(midToken, destToken, rets, flags);
return (rets, gas1 + gas2);
}
function _calculateNoReturn(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
this;
return (new uint256[](parts), 0);
}
}
contract OneSplitBaseWrap is IOneSplit, OneSplitRoot {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags // See constants in IOneSplit.sol
) internal {
if (fromToken == destToken) {
return;
}
_swapFloor(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _swapFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 /*flags*/ // See constants in IOneSplit.sol
) internal;
}
contract OneSplit is IOneSplit, OneSplitRoot {
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplitView) public {
oneSplitView = _oneSplitView;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags // See constants in IOneSplit.sol
) public payable returns(uint256 returnAmount) {
if (fromToken == destToken) {
return amount;
}
function(IERC20,IERC20,uint256,uint256)[DEXES_COUNT] memory reserves = [
_swapOnUniswap,
_swapOnNowhere,
_swapOnBancor,
_swapOnOasis,
_swapOnCurveCompound,
_swapOnCurveUSDT,
_swapOnCurveY,
_swapOnCurveBinance,
_swapOnCurveSynthetix,
_swapOnUniswapCompound,
_swapOnUniswapChai,
_swapOnUniswapAave,
_swapOnMooniswap,
_swapOnUniswapV2,
_swapOnUniswapV2ETH,
_swapOnUniswapV2DAI,
_swapOnUniswapV2USDC,
_swapOnCurvePAX,
_swapOnCurveRenBTC,
_swapOnCurveTBTC,
_swapOnDforceSwap,
_swapOnShell,
_swapOnMStableMUSD,
_swapOnCurveSBTC,
_swapOnBalancer1,
_swapOnBalancer2,
_swapOnBalancer3,
_swapOnKyber1,
_swapOnKyber2,
_swapOnKyber3,
_swapOnKyber4,
_swapOnMooniswapETH,
_swapOnMooniswapDAI,
_swapOnMooniswapUSDC
];
require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size");
uint256 parts = 0;
uint256 lastNonZeroIndex = 0;
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] > 0) {
parts = parts.add(distribution[i]);
lastNonZeroIndex = i;
}
}
if (parts == 0) {
if (fromToken.isETH()) {
msg.sender.transfer(msg.value);
return msg.value;
}
return amount;
}
fromToken.universalTransferFrom(msg.sender, address(this), amount);
uint256 remainingAmount = fromToken.universalBalanceOf(address(this));
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] == 0) {
continue;
}
uint256 swapAmount = amount.mul(distribution[i]).div(parts);
if (i == lastNonZeroIndex) {
swapAmount = remainingAmount;
}
remainingAmount -= swapAmount;
reserves[i](fromToken, destToken, swapAmount, flags);
}
returnAmount = destToken.universalBalanceOf(address(this));
require(returnAmount >= minReturn, "OneSplit: Return amount was not enough");
destToken.universalTransfer(msg.sender, returnAmount);
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
}
// Swap helpers
function _swapOnCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveCompound), amount);
curveCompound.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveUSDT(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveUSDT), amount);
curveUSDT.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == tusd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == tusd ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveY), amount);
curveY.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == busd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == busd ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveBinance), amount);
curveBinance.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == susd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == susd ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveSynthetix), amount);
curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurvePAX(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == pax ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == pax ? 4 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curvePAX), amount);
curvePAX.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnShell(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
fromToken.universalApprove(address(shell), amount);
shell.swapByOrigin(
address(fromToken),
address(destToken),
amount,
0,
now + 50
);
}
function _swapOnMStableMUSD(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
fromToken.universalApprove(address(musd), amount);
musd.swap(
fromToken,
destToken,
amount,
address(this)
);
}
function _swapOnCurveRenBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == renbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0);
int128 j = (destToken == renbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveRenBTC), amount);
curveRenBTC.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnCurveTBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == tbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0) +
(fromToken == hbtc ? 3 : 0);
int128 j = (destToken == tbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0) +
(destToken == hbtc ? 3 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveTBTC), amount);
curveTBTC.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnCurveSBTC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
int128 i = (fromToken == renbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0) +
(fromToken == sbtc ? 3 : 0);
int128 j = (destToken == renbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0) +
(destToken == sbtc ? 3 : 0);
if (i == 0 || j == 0) {
return;
}
fromToken.universalApprove(address(curveSBTC), amount);
curveSBTC.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnDforceSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
fromToken.universalApprove(address(dforceSwap), amount);
dforceSwap.swap(fromToken, destToken, amount);
}
function _swapOnUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
uint256 returnAmount = amount;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange != IUniswapExchange(0)) {
fromToken.universalApprove(address(fromExchange), returnAmount);
returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now);
}
}
if (!destToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
if (toExchange != IUniswapExchange(0)) {
returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now);
}
}
}
function _swapOnUniswapCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
if (!fromToken.isETH()) {
ICompoundToken fromCompound = compoundRegistry.cTokenByToken(fromToken);
fromToken.universalApprove(address(fromCompound), amount);
fromCompound.mint(amount);
_swapOnUniswap(IERC20(fromCompound), destToken, IERC20(fromCompound).universalBalanceOf(address(this)), flags);
return;
}
if (!destToken.isETH()) {
ICompoundToken toCompound = compoundRegistry.cTokenByToken(destToken);
_swapOnUniswap(fromToken, IERC20(toCompound), amount, flags);
toCompound.redeem(IERC20(toCompound).universalBalanceOf(address(this)));
destToken.universalBalanceOf(address(this));
return;
}
}
function _swapOnUniswapChai(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
if (fromToken == dai) {
fromToken.universalApprove(address(chai), amount);
chai.join(address(this), amount);
_swapOnUniswap(IERC20(chai), destToken, IERC20(chai).universalBalanceOf(address(this)), flags);
return;
}
if (destToken == dai) {
_swapOnUniswap(fromToken, IERC20(chai), amount, flags);
chai.exit(address(this), chai.balanceOf(address(this)));
return;
}
}
function _swapOnUniswapAave(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
if (!fromToken.isETH()) {
IAaveToken fromAave = aaveRegistry.aTokenByToken(fromToken);
fromToken.universalApprove(aave.core(), amount);
aave.deposit(fromToken, amount, 1101);
_swapOnUniswap(IERC20(fromAave), destToken, IERC20(fromAave).universalBalanceOf(address(this)), flags);
return;
}
if (!destToken.isETH()) {
IAaveToken toAave = aaveRegistry.aTokenByToken(destToken);
_swapOnUniswap(fromToken, IERC20(toAave), amount, flags);
toAave.redeem(toAave.balanceOf(address(this)));
return;
}
}
function _swapOnMooniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
IMooniswap mooniswap = mooniswapRegistry.pools(
fromToken.isETH() ? ZERO_ADDRESS : fromToken,
destToken.isETH() ? ZERO_ADDRESS : destToken
);
fromToken.universalApprove(address(mooniswap), amount);
mooniswap.swap.value(fromToken.isETH() ? amount : 0)(
fromToken.isETH() ? ZERO_ADDRESS : fromToken,
destToken.isETH() ? ZERO_ADDRESS : destToken,
amount,
0,
0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5
);
}
function _swapOnMooniswapETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnMooniswap(fromToken, ZERO_ADDRESS, amount, flags);
_swapOnMooniswap(ZERO_ADDRESS, destToken, address(this).balance, flags);
}
function _swapOnMooniswapDAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnMooniswap(fromToken, dai, amount, flags);
_swapOnMooniswap(dai, destToken, dai.balanceOf(address(this)), flags);
}
function _swapOnMooniswapUSDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnMooniswap(fromToken, usdc, amount, flags);
_swapOnMooniswap(usdc, destToken, usdc.balanceOf(address(this)), flags);
}
function _swapOnNowhere(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 /*flags*/
) internal {
revert("This source was deprecated");
}
function _swapOnKyber1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
0xff4b796265722046707200000000000000000000000000000000000000000000
);
}
function _swapOnKyber2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
0xffabcd0000000000000000000000000000000000000000000000000000000000
);
}
function _swapOnKyber3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
0xff4f6e65426974205175616e7400000000000000000000000000000000000000
);
}
function _swapOnKyber4(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnKyber(
fromToken,
destToken,
amount,
flags,
_kyberReserveIdByTokens(fromToken, destToken)
);
}
function _swapOnKyber(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags,
bytes32 reserveId
) internal {
uint256 returnAmount = amount;
bytes32[] memory reserveIds = new bytes32[](1);
reserveIds[0] = reserveId;
if (!fromToken.isETH()) {
bytes memory fromHint = kyberHintHandler.buildTokenToEthHint(
fromToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
);
fromToken.universalApprove(address(kyberNetworkProxy), amount);
returnAmount = kyberNetworkProxy.tradeWithHintAndFee(
fromToken,
returnAmount,
ETH_ADDRESS,
address(this),
uint256(-1),
0,
0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5,
(flags >> 255) * 10,
fromHint
);
}
if (!destToken.isETH()) {
bytes memory destHint = kyberHintHandler.buildEthToTokenHint(
destToken,
IKyberHintHandler.TradeType.MaskIn,
reserveIds,
new uint256[](0)
);
returnAmount = kyberNetworkProxy.tradeWithHintAndFee.value(returnAmount)(
ETH_ADDRESS,
returnAmount,
destToken,
address(this),
uint256(-1),
0,
0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5,
(flags >> 255) * 10,
destHint
);
}
}
function _swapOnBancor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
address[] memory path = bancorNetworkPathFinder.generatePath(
fromToken.isETH() ? bancorEtherToken : fromToken,
destToken.isETH() ? bancorEtherToken : destToken
);
fromToken.universalApprove(address(bancorNetwork), amount);
bancorNetwork.convert.value(fromToken.isETH() ? amount : 0)(path, amount, 1);
}
function _swapOnOasis(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal {
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
IERC20 approveToken = fromToken.isETH() ? weth : fromToken;
approveToken.universalApprove(address(oasisExchange), amount);
oasisExchange.sellAllAmount(
fromToken.isETH() ? weth : fromToken,
amount,
destToken.isETH() ? weth : destToken,
1
);
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnUniswapV2Internal(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) internal returns(uint256 returnAmount) {
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
IERC20 toTokenReal = destToken.isETH() ? weth : destToken;
IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal);
bool needSync;
bool needSkim;
(returnAmount, needSync, needSkim) = exchange.getReturn(fromTokenReal, toTokenReal, amount);
if (needSync) {
exchange.sync();
}
else if (needSkim) {
exchange.skim(0x68a17B587CAF4f9329f0e372e3A78D23A46De6b5);
}
fromTokenReal.universalTransfer(address(exchange), amount);
if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) {
exchange.swap(0, returnAmount, address(this), "");
} else {
exchange.swap(returnAmount, 0, address(this), "");
}
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnUniswapV2OverMid(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2Internal(
midToken,
destToken,
_swapOnUniswapV2Internal(
fromToken,
midToken,
amount,
flags
),
flags
);
}
function _swapOnUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2Internal(
fromToken,
destToken,
amount,
flags
);
}
function _swapOnUniswapV2ETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2OverMid(
fromToken,
weth,
destToken,
amount,
flags
);
}
function _swapOnUniswapV2DAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2OverMid(
fromToken,
dai,
destToken,
amount,
flags
);
}
function _swapOnUniswapV2USDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnUniswapV2OverMid(
fromToken,
usdc,
destToken,
amount,
flags
);
}
function _swapOnBalancerX(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/,
uint256 poolIndex
) internal {
address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
address(fromToken.isETH() ? weth : fromToken),
address(destToken.isETH() ? weth : destToken),
poolIndex + 1
);
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
(fromToken.isETH() ? weth : fromToken).universalApprove(pools[poolIndex], amount);
IBalancerPool(pools[poolIndex]).swapExactAmountIn(
fromToken.isETH() ? weth : fromToken,
amount,
destToken.isETH() ? weth : destToken,
0,
uint256(-1)
);
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnBalancer1(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnBalancerX(fromToken, destToken, amount, flags, 0);
}
function _swapOnBalancer2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnBalancerX(fromToken, destToken, amount, flags, 1);
}
function _swapOnBalancer3(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal {
_swapOnBalancerX(fromToken, destToken, amount, flags, 2);
}
}
// File: contracts/OneSplitCompound.sol
pragma solidity ^0.5.0;
contract OneSplitCompoundView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _compoundGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _compoundGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
if (underlying != IERC20(0)) {
uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored();
(returnAmount, estimateGasAmount, distribution) = _compoundGetExpectedReturn(
underlying,
destToken,
amount.mul(compoundRate).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
if (underlying != IERC20(0)) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
uint256 compoundRate = ICompoundToken(address(destToken)).exchangeRateStored();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice.mul(compoundRate).div(1e18)
);
return (returnAmount.mul(1e18).div(compoundRate), estimateGasAmount + 430_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitCompound is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_compoundSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _compoundSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
if (underlying != IERC20(0)) {
ICompoundToken(address(fromToken)).redeem(amount);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return _compoundSwap(
underlying,
destToken,
underlyingAmount,
distribution,
flags
);
}
underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
if (underlying != IERC20(0)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
cETH.mint.value(underlyingAmount)();
} else {
underlying.universalApprove(address(destToken), underlyingAmount);
ICompoundToken(address(destToken)).mint(underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IFulcrum.sol
pragma solidity ^0.5.0;
contract IFulcrumToken is IERC20 {
function tokenPrice() external view returns (uint256);
function loanTokenAddress() external view returns (address);
function mintWithEther(address receiver) external payable returns (uint256 mintAmount);
function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
function burnToEther(address receiver, uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
}
// File: contracts/OneSplitFulcrum.sol
pragma solidity ^0.5.0;
contract OneSplitFulcrumBase {
using UniversalERC20 for IERC20;
function _isFulcrumToken(IERC20 token) internal view returns(IERC20) {
if (token.isETH()) {
return IERC20(-1);
}
(bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSignature(
"name()"
));
if (!success) {
return IERC20(-1);
}
bool foundBZX = false;
for (uint i = 0; i + 6 < data.length; i++) {
if (data[i + 0] == "F" &&
data[i + 1] == "u" &&
data[i + 2] == "l" &&
data[i + 3] == "c" &&
data[i + 4] == "r" &&
data[i + 5] == "u" &&
data[i + 6] == "m")
{
foundBZX = true;
break;
}
}
if (!foundBZX) {
return IERC20(-1);
}
(success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
IFulcrumToken(address(token)).loanTokenAddress.selector
));
if (!success) {
return IERC20(-1);
}
return abi.decode(data, (IERC20));
}
}
contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _fulcrumGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _fulcrumGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice();
(returnAmount, estimateGasAmount, distribution) = _fulcrumGetExpectedReturn(
underlying,
destToken,
amount.mul(fulcrumRate).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 381_000, distribution);
}
underlying = _isFulcrumToken(destToken);
if (underlying != IERC20(-1)) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
uint256 fulcrumRate = IFulcrumToken(address(destToken)).tokenPrice();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice.mul(fulcrumRate).div(1e18)
);
return (returnAmount.mul(1e18).div(fulcrumRate), estimateGasAmount + 354_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_fulcrumSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _fulcrumSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
if (underlying.isETH()) {
IFulcrumToken(address(fromToken)).burnToEther(address(this), amount);
} else {
IFulcrumToken(address(fromToken)).burn(address(this), amount);
}
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return super._swap(
underlying,
destToken,
underlyingAmount,
distribution,
flags
);
}
underlying = _isFulcrumToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
IFulcrumToken(address(destToken)).mintWithEther.value(underlyingAmount)(address(this));
} else {
underlying.universalApprove(address(destToken), underlyingAmount);
IFulcrumToken(address(destToken)).mint(address(this), underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitChai.sol
pragma solidity ^0.5.0;
contract OneSplitChaiView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
dai,
destToken,
chai.chaiToDai(amount),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 197_000, distribution);
}
if (destToken == IERC20(chai)) {
uint256 price = chai.chaiPrice();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
dai,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice.mul(1e18).div(price)
);
return (returnAmount.mul(price).div(1e18), estimateGasAmount + 168_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitChai is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
chai.exit(address(this), amount);
return super._swap(
dai,
destToken,
dai.balanceOf(address(this)),
distribution,
flags
);
}
if (destToken == IERC20(chai)) {
super._swap(
fromToken,
dai,
amount,
distribution,
flags
);
uint256 daiBalance = dai.balanceOf(address(this));
dai.universalApprove(address(chai), daiBalance);
chai.join(address(this), daiBalance);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IBdai.sol
pragma solidity ^0.5.0;
contract IBdai is IERC20 {
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/OneSplitBdai.sol
pragma solidity ^0.5.0;
contract OneSplitBdaiBase {
IBdai internal constant bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8);
IERC20 internal constant btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f);
}
contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
dai,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 227_000, distribution);
}
if (destToken == IERC20(bdai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
dai,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
bdai.exit(amount);
uint256 btuBalance = btu.balanceOf(address(this));
if (btuBalance > 0) {
(,uint256[] memory btuDistribution) = getExpectedReturn(
btu,
destToken,
btuBalance,
1,
flags
);
_swap(
btu,
destToken,
btuBalance,
btuDistribution,
flags
);
}
return super._swap(
dai,
destToken,
amount,
distribution,
flags
);
}
if (destToken == IERC20(bdai)) {
super._swap(fromToken, dai, amount, distribution, flags);
uint256 daiBalance = dai.balanceOf(address(this));
dai.universalApprove(address(bdai), daiBalance);
bdai.join(daiBalance);
return;
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIearn.sol
pragma solidity ^0.5.0;
contract IIearn is IERC20 {
function token() external view returns(IERC20);
function calcPoolValueInToken() external view returns(uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/OneSplitIearn.sol
pragma solidity ^0.5.0;
contract OneSplitIearnBase {
function _yTokens() internal pure returns(IIearn[13] memory) {
return [
IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01),
IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9),
IIearn(0x73a052500105205d34Daf004eAb301916DA8190f),
IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D),
IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e),
IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600),
IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE),
IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32),
IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447),
IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951),
IIearn(0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc),
IIearn(0x9777d7E2b60bB01759D0E2f8be2095df444cb07E),
IIearn(0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59)
];
}
}
contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _iearnGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _iearnGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IEARN)) {
IIearn[13] memory yTokens = _yTokens();
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
(returnAmount, estimateGasAmount, distribution) = _iearnGetExpectedReturn(
yTokens[i].token(),
destToken,
amount
.mul(yTokens[i].calcPoolValueInToken())
.div(yTokens[i].totalSupply()),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 260_000, distribution);
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (destToken == IERC20(yTokens[i])) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
IERC20 token = yTokens[i].token();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
token,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice
.mul(yTokens[i].calcPoolValueInToken())
.div(yTokens[i].totalSupply())
);
return(
returnAmount
.mul(yTokens[i].totalSupply())
.div(yTokens[i].calcPoolValueInToken()),
estimateGasAmount + 743_000,
distribution
);
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_iearnSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _iearnSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_IEARN)) {
IIearn[13] memory yTokens = _yTokens();
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
yTokens[i].withdraw(amount);
_iearnSwap(underlying, destToken, underlying.balanceOf(address(this)), distribution, flags);
return;
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (destToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
uint256 underlyingBalance = underlying.balanceOf(address(this));
underlying.universalApprove(address(yTokens[i]), underlyingBalance);
yTokens[i].deposit(underlyingBalance);
return;
}
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIdle.sol
pragma solidity ^0.5.0;
contract IIdle is IERC20 {
function token()
external view returns (IERC20);
function tokenPrice()
external view returns (uint256);
function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 mintedTokens);
function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 redeemedTokens);
}
// File: contracts/OneSplitIdle.sol
pragma solidity ^0.5.0;
contract OneSplitIdleBase {
function _idleTokens() internal pure returns(IIdle[8] memory) {
// https://developers.idle.finance/contracts-and-codebase
return [
// V3
IIdle(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934),
IIdle(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6),
IIdle(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D),
IIdle(0x1846bdfDB6A0f5c473dEc610144513bd071999fB),
IIdle(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C),
IIdle(0x42740698959761BAF1B06baa51EfBD88CB1D862B),
// V2
IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD),
IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991)
];
}
}
contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _idleGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _idleGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
IIdle[8] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
(returnAmount, estimateGasAmount, distribution) = _idleGetExpectedReturn(
tokens[i].token(),
destToken,
amount.mul(tokens[i].tokenPrice()).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 2_400_000, distribution);
}
}
for (uint i = 0; i < tokens.length; i++) {
if (destToken == IERC20(tokens[i])) {
uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
uint256 _price = tokens[i].tokenPrice();
IERC20 token = tokens[i].token();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
token,
amount,
parts,
flags,
_destTokenEthPriceTimesGasPrice.mul(_price).div(1e18)
);
return (returnAmount.mul(1e18).div(_price), estimateGasAmount + 1_300_000, distribution);
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_idleSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _idleSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
IIdle[8] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0));
_idleSwap(underlying, destToken, minted, distribution, flags);
return;
}
}
for (uint i = 0; i < tokens.length; i++) {
if (destToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
uint256 underlyingBalance = underlying.balanceOf(address(this));
underlying.universalApprove(address(tokens[i]), underlyingBalance);
tokens[i].mintIdleToken(underlyingBalance, new uint256[](0));
return;
}
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/OneSplitAave.sol
pragma solidity ^0.5.0;
contract OneSplitAaveView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _aaveGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _aaveGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
if (underlying != IERC20(0)) {
(returnAmount, estimateGasAmount, distribution) = _aaveGetExpectedReturn(
underlying,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 670_000, distribution);
}
underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
if (underlying != IERC20(0)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 310_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitAave is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_aaveSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _aaveSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
if (underlying != IERC20(0)) {
IAaveToken(address(fromToken)).redeem(amount);
return _aaveSwap(
underlying,
destToken,
amount,
distribution,
flags
);
}
underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
if (underlying != IERC20(0)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
underlying.universalApprove(aave.core(), underlyingAmount);
aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)(
underlying.isETH() ? ETH_ADDRESS : underlying,
underlyingAmount,
1101
);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitWeth.sol
pragma solidity ^0.5.0;
contract OneSplitWethView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _wethGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _wethGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == weth || fromToken == bancorEtherToken) {
return super.getExpectedReturnWithGas(ETH_ADDRESS, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice);
}
if (destToken == weth || destToken == bancorEtherToken) {
return super.getExpectedReturnWithGas(fromToken, ETH_ADDRESS, amount, parts, flags, destTokenEthPriceTimesGasPrice);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitWeth is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_wethSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _wethSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == weth) {
weth.withdraw(weth.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
destToken,
amount,
distribution,
flags
);
return;
}
if (fromToken == bancorEtherToken) {
bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
destToken,
amount,
distribution,
flags
);
return;
}
if (destToken == weth) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
weth.deposit.value(address(this).balance)();
return;
}
if (destToken == bancorEtherToken) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
bancorEtherToken.deposit.value(address(this).balance)();
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitMStable.sol
pragma solidity ^0.5.0;
contract OneSplitMStableView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
if (fromToken == IERC20(musd)) {
{
(bool valid1,, uint256 res1,) = musd_helper.getRedeemValidity(musd, amount, destToken);
if (valid1) {
return (res1, 300_000, new uint256[](DEXES_COUNT));
}
}
(bool valid,, address token) = musd_helper.suggestRedeemAsset(musd);
if (valid) {
(,, returnAmount,) = musd_helper.getRedeemValidity(musd, amount, IERC20(token));
if (IERC20(token) != destToken) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
IERC20(token),
destToken,
returnAmount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
} else {
distribution = new uint256[](DEXES_COUNT);
}
return (returnAmount, estimateGasAmount + 300_000, distribution);
}
}
if (destToken == IERC20(musd)) {
if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
(,, returnAmount) = musd.getSwapOutput(fromToken, destToken, amount);
return (returnAmount, 300_000, new uint256[](DEXES_COUNT));
}
else {
IERC20 _destToken = destToken;
(bool valid,, address token) = musd_helper.suggestMintAsset(_destToken);
if (valid) {
if (IERC20(token) != fromToken) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
IERC20(token),
amount,
parts,
flags,
_scaleDestTokenEthPriceTimesGasPrice(
_destToken,
IERC20(token),
destTokenEthPriceTimesGasPrice
)
);
} else {
returnAmount = amount;
}
(,, returnAmount) = musd.getSwapOutput(IERC20(token), _destToken, returnAmount);
return (returnAmount, estimateGasAmount + 300_000, distribution);
}
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitMStable is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
if (fromToken == IERC20(musd)) {
if (destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd) {
(,,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, destToken);
musd.redeem(
destToken,
result
);
}
else {
(,,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, dai);
musd.redeem(
dai,
result
);
super._swap(
dai,
destToken,
dai.balanceOf(address(this)),
distribution,
flags
);
}
return;
}
if (destToken == IERC20(musd)) {
if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
fromToken.universalApprove(address(musd), amount);
musd.swap(
fromToken,
destToken,
amount,
address(this)
);
}
else {
super._swap(
fromToken,
dai,
amount,
distribution,
flags
);
musd.swap(
dai,
destToken,
dai.balanceOf(address(this)),
address(this)
);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IDMM.sol
pragma solidity ^0.5.0;
interface IDMMController {
function getUnderlyingTokenForDmm(IERC20 token) external view returns(IERC20);
}
contract IDMM is IERC20 {
function getCurrentExchangeRate() public view returns(uint256);
function mint(uint256 underlyingAmount) public returns(uint256);
function redeem(uint256 amount) public returns(uint256);
}
// File: contracts/OneSplitDMM.sol
pragma solidity ^0.5.0;
contract OneSplitDMMBase {
IDMMController internal constant _dmmController = IDMMController(0x4CB120Dd1D33C9A3De8Bc15620C7Cd43418d77E2);
function _getDMMUnderlyingToken(IERC20 token) internal view returns(IERC20) {
(bool success, bytes memory data) = address(_dmmController).staticcall(
abi.encodeWithSelector(
_dmmController.getUnderlyingTokenForDmm.selector,
token
)
);
if (!success || data.length == 0) {
return IERC20(-1);
}
return abi.decode(data, (IERC20));
}
function _getDMMExchangeRate(IDMM dmm) internal view returns(uint256) {
(bool success, bytes memory data) = address(dmm).staticcall(
abi.encodeWithSelector(
dmm.getCurrentExchangeRate.selector
)
);
if (!success || data.length == 0) {
return 0;
}
return abi.decode(data, (uint256));
}
}
contract OneSplitDMMView is OneSplitViewWrapBase, OneSplitDMMBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _dmmGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _dmmGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
IERC20 underlying = _getDMMUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
if (underlying == weth) {
underlying = ETH_ADDRESS;
}
IERC20 _fromToken = fromToken;
(returnAmount, estimateGasAmount, distribution) = _dmmGetExpectedReturn(
underlying,
destToken,
amount.mul(_getDMMExchangeRate(IDMM(address(_fromToken)))).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
underlying = _getDMMUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
if (underlying == weth) {
underlying = ETH_ADDRESS;
}
uint256 price = _getDMMExchangeRate(IDMM(address(destToken)));
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice.mul(price).div(1e18)
);
return (
returnAmount.mul(1e18).div(price),
estimateGasAmount + 430_000,
distribution
);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitDMM is OneSplitBaseWrap, OneSplitDMMBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_dmmSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _dmmSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
IERC20 underlying = _getDMMUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
IDMM(address(fromToken)).redeem(amount);
uint256 balance = underlying.universalBalanceOf(address(this));
if (underlying == weth) {
weth.withdraw(balance);
}
_dmmSwap(
(underlying == weth) ? ETH_ADDRESS : underlying,
destToken,
balance,
distribution,
flags
);
}
underlying = _getDMMUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
(underlying == weth) ? ETH_ADDRESS : underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = ((underlying == weth) ? ETH_ADDRESS : underlying).universalBalanceOf(address(this));
if (underlying == weth) {
weth.deposit.value(underlyingAmount);
}
underlying.universalApprove(address(destToken), underlyingAmount);
IDMM(address(destToken)).mint(underlyingAmount);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitMooniswapPoolToken.sol
pragma solidity ^0.5.0;
contract OneSplitMooniswapTokenBase {
using SafeMath for uint256;
using Math for uint256;
using UniversalERC20 for IERC20;
struct TokenInfo {
IERC20 token;
uint256 reserve;
}
struct PoolDetails {
TokenInfo[2] tokens;
uint256 totalSupply;
}
function _getPoolDetails(IMooniswap pool) internal view returns (PoolDetails memory details) {
for (uint i = 0; i < 2; i++) {
IERC20 token = pool.tokens(i);
details.tokens[i] = TokenInfo({
token: token,
reserve: token.universalBalanceOf(address(pool))
});
}
details.totalSupply = IERC20(address(pool)).totalSupply();
}
}
contract OneSplitMooniswapTokenView is OneSplitViewWrapBase, OneSplitMooniswapTokenBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns (
uint256 returnAmount,
uint256,
uint256[] memory distribution
)
{
if (fromToken.eq(toToken)) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_MOONISWAP_POOL_TOKEN)) {
bool isPoolTokenFrom = mooniswapRegistry.isPool(address(fromToken));
bool isPoolTokenTo = mooniswapRegistry.isPool(address(toToken));
if (isPoolTokenFrom && isPoolTokenTo) {
(
uint256 returnETHAmount,
uint256[] memory poolTokenFromDistribution
) = _getExpectedReturnFromMooniswapPoolToken(
fromToken,
ETH_ADDRESS,
amount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
(
uint256 returnPoolTokenToAmount,
uint256[] memory poolTokenToDistribution
) = _getExpectedReturnToMooniswapPoolToken(
ETH_ADDRESS,
toToken,
returnETHAmount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
for (uint i = 0; i < poolTokenToDistribution.length; i++) {
poolTokenFromDistribution[i] |= poolTokenToDistribution[i] << 128;
}
return (returnPoolTokenToAmount, 0, poolTokenFromDistribution);
}
if (isPoolTokenFrom) {
(returnAmount, distribution) = _getExpectedReturnFromMooniswapPoolToken(
fromToken,
toToken,
amount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
return (returnAmount, 0, distribution);
}
if (isPoolTokenTo) {
(returnAmount, distribution) = _getExpectedReturnToMooniswapPoolToken(
fromToken,
toToken,
amount,
parts,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
return (returnAmount, 0, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
toToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnFromMooniswapPoolToken(
IERC20 poolToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
PoolDetails memory details = _getPoolDetails(IMooniswap(address(poolToken)));
for (uint i = 0; i < 2; i++) {
uint256 exchangeAmount = amount
.mul(details.tokens[i].reserve)
.div(details.totalSupply);
if (toToken.eq(details.tokens[i].token)) {
returnAmount = returnAmount.add(exchangeAmount);
continue;
}
(uint256 ret, ,uint256[] memory dist) = super.getExpectedReturnWithGas(
details.tokens[i].token,
toToken,
exchangeAmount,
parts,
flags,
0
);
returnAmount = returnAmount.add(ret);
for (uint j = 0; j < distribution.length; j++) {
distribution[j] |= dist[j] << (i * 8);
}
}
return (returnAmount, distribution);
}
function _getExpectedReturnToMooniswapPoolToken(
IERC20 fromToken,
IERC20 poolToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
PoolDetails memory details = _getPoolDetails(IMooniswap(address(poolToken)));
// will overwritten to liquidity amounts
uint256[2] memory amounts;
amounts[0] = amount.div(2);
amounts[1] = amount.sub(amounts[0]);
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < 2; i++) {
if (fromToken.eq(details.tokens[i].token)) {
continue;
}
(amounts[i], ,dist) = super.getExpectedReturnWithGas(
fromToken,
details.tokens[i].token,
amounts[i],
parts,
flags,
0
);
for (uint j = 0; j < distribution.length; j++) {
distribution[j] |= dist[j] << (i * 8);
}
}
returnAmount = uint256(-1);
for (uint i = 0; i < 2; i++) {
returnAmount = Math.min(
returnAmount,
details.totalSupply.mul(amounts[i]).div(details.tokens[i].reserve)
);
}
return (
returnAmount,
distribution
);
}
}
contract OneSplitMooniswapToken is OneSplitBaseWrap, OneSplitMooniswapTokenBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken.eq(toToken)) {
return;
}
if (!flags.check(FLAG_DISABLE_MOONISWAP_POOL_TOKEN)) {
bool isPoolTokenFrom = mooniswapRegistry.isPool(address(fromToken));
bool isPoolTokenTo = mooniswapRegistry.isPool(address(toToken));
if (isPoolTokenFrom && isPoolTokenTo) {
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] & ((1 << 128) - 1);
}
uint256 ethBalanceBefore = ETH_ADDRESS.universalBalanceOf(address(this));
_swapFromMooniswapToken(
fromToken,
ETH_ADDRESS,
amount,
dist,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] >> 128;
}
uint256 ethBalanceAfter = ETH_ADDRESS.universalBalanceOf(address(this));
return _swapToMooniswapToken(
ETH_ADDRESS,
toToken,
ethBalanceAfter.sub(ethBalanceBefore),
dist,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
}
if (isPoolTokenFrom) {
return _swapFromMooniswapToken(
fromToken,
toToken,
amount,
distribution,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
}
if (isPoolTokenTo) {
return _swapToMooniswapToken(
fromToken,
toToken,
amount,
distribution,
FLAG_DISABLE_MOONISWAP_POOL_TOKEN
);
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _swapFromMooniswapToken(
IERC20 poolToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
IERC20[2] memory tokens = [
IMooniswap(address(poolToken)).tokens(0),
IMooniswap(address(poolToken)).tokens(1)
];
IMooniswap(address(poolToken)).withdraw(
amount,
new uint256[](0)
);
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < 2; i++) {
if (toToken.eq(tokens[i])) {
continue;
}
for (uint j = 0; j < distribution.length; j++) {
dist[j] = (distribution[j] >> (i * 8)) & 0xFF;
}
super._swap(
tokens[i],
toToken,
tokens[i].universalBalanceOf(address(this)),
dist,
flags
);
}
}
function _swapToMooniswapToken(
IERC20 fromToken,
IERC20 poolToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
IERC20[2] memory tokens = [
IMooniswap(address(poolToken)).tokens(0),
IMooniswap(address(poolToken)).tokens(1)
];
// will overwritten to liquidity amounts
uint256[] memory amounts = new uint256[](2);
amounts[0] = amount.div(2);
amounts[1] = amount.sub(amounts[0]);
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < 2; i++) {
if (fromToken.eq(tokens[i])) {
continue;
}
for (uint j = 0; j < distribution.length; j++) {
dist[j] = (distribution[j] >> (i * 8)) & 0xFF;
}
super._swap(
fromToken,
tokens[i],
amounts[i],
dist,
flags
);
amounts[i] = tokens[i].universalBalanceOf(address(this));
tokens[i].universalApprove(address(poolToken), amounts[i]);
}
uint256 ethValue = (tokens[0].isETH() ? amounts[0] : 0) + (tokens[1].isETH() ? amounts[1] : 0);
IMooniswap(address(poolToken)).deposit.value(ethValue)(
amounts,
new uint256[](2)
);
for (uint i = 0; i < 2; i++) {
tokens[i].universalTransfer(
msg.sender,
tokens[i].universalBalanceOf(address(this))
);
}
}
}
// File: contracts/OneSplit.sol
pragma solidity ^0.5.0;
contract OneSplitViewWrap is
OneSplitViewWrapBase,
OneSplitMStableView,
OneSplitChaiView,
OneSplitBdaiView,
OneSplitAaveView,
OneSplitFulcrumView,
OneSplitCompoundView,
OneSplitIearnView,
OneSplitIdleView,
OneSplitWethView,
OneSplitDMMView,
OneSplitMooniswapTokenView
{
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplit) public {
oneSplitView = _oneSplit;
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnRespectingGasFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitWrap is
OneSplitBaseWrap,
OneSplitMStable,
OneSplitChai,
OneSplitBdai,
OneSplitAave,
OneSplitFulcrum,
OneSplitCompound,
OneSplitIearn,
OneSplitIdle,
OneSplitWeth,
OneSplitDMM,
OneSplitMooniswapToken
{
IOneSplitView public oneSplitView;
IOneSplit public oneSplit;
constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public {
oneSplitView = _oneSplitView;
oneSplit = _oneSplit;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
uint256[] memory dist;
returnAmounts = new uint256[](tokens.length - 1);
for (uint i = 1; i < tokens.length; i++) {
if (tokens[i - 1] == tokens[i]) {
returnAmounts[i - 1] = (i == 1) ? amount : returnAmounts[i - 2];
continue;
}
IERC20[] memory _tokens = tokens;
(
returnAmounts[i - 1],
amount,
dist
) = getExpectedReturnWithGas(
_tokens[i - 1],
_tokens[i],
(i == 1) ? amount : returnAmounts[i - 2],
parts[i - 1],
flags[i - 1],
destTokenEthPriceTimesGasPrices[i - 1]
);
estimateGasAmount = estimateGasAmount.add(amount);
if (distribution.length == 0) {
distribution = new uint256[](dist.length);
}
for (uint j = 0; j < distribution.length; j++) {
distribution[j] = distribution[j].add(dist[j] << (8 * (i - 1)));
}
}
}
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable returns(uint256 returnAmount) {
fromToken.universalTransferFrom(msg.sender, address(this), amount);
uint256 confirmed = fromToken.universalBalanceOf(address(this));
_swap(fromToken, destToken, confirmed, distribution, flags);
returnAmount = destToken.universalBalanceOf(address(this));
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
destToken.universalTransfer(msg.sender, returnAmount);
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
}
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
) public payable returns(uint256 returnAmount) {
tokens[0].universalTransferFrom(msg.sender, address(this), amount);
returnAmount = tokens[0].universalBalanceOf(address(this));
for (uint i = 1; i < tokens.length; i++) {
if (tokens[i - 1] == tokens[i]) {
continue;
}
uint256[] memory dist = new uint256[](distribution.length);
for (uint j = 0; j < distribution.length; j++) {
dist[j] = (distribution[j] >> (8 * (i - 1))) & 0xFF;
}
_swap(
tokens[i - 1],
tokens[i],
returnAmount,
dist,
flags[i - 1]
);
returnAmount = tokens[i].universalBalanceOf(address(this));
tokens[i - 1].universalTransfer(msg.sender, tokens[i - 1].universalBalanceOf(address(this)));
}
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
tokens[tokens.length - 1].universalTransfer(msg.sender, returnAmount);
}
function _swapFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
fromToken.universalApprove(address(oneSplit), amount);
oneSplit.swap.value(fromToken.isETH() ? amount : 0)(
fromToken,
destToken,
amount,
0,
distribution,
flags
);
}
}File 7 of 14: ChiToken
/*
,╖╗#▒▓▓▓▓▓╣╬╣▓▓▓▓▒#╗╗╓,
,╗@▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╗╖
╓#▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╠╠▄╣╝╜"""╙╙▀╝╝╣╬╬╬╬▓▌╖
╓▓╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀`╓å▓▓▓╙ ,▄▓▓██▓▓▓▄▄▄▄▄╠╠╙╠▄▄
╓@╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌ ê`' *▀▀▀▀▀▀▀▓██████████████▄
╔▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╙▀████████████▌
╓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╙████████████▌
,▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▀ ╗▄█████████████▄
é╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌ #╙ ╙▀█████████████▓
╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀ ╙▓╬╣▓▄ ╙▀▀███████████µ
▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀╣╝╙ ╒▓╬╬╬╬╬╬▓ ╙████████████████µ
▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌ ╖╖╖▄▓╬╬╬╬╬╬╬▓ █████████████████µ
╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ,#▓╣╬╬▓╬╬╬╬╬╬╬╬╬╬╬╬▌ ▓█████████████████
]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╓╖ ]╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣╨ ██████████████████▌
▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌╖, ╙╠╠▓╬╬╬╬╬╬╬╬╬▓╝╙ ╫███████████████████
]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙ ▓████████████████████▌
║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙` ▄███████████████████████
╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╝▀╙ ,▄█████████████████████████
╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝╜` ▄▓████████████████████████████
║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣▀` ,▄▄▓████████████████████████████████
▐╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙ ,,,▄╠▓██████████████████████████████▌
╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙╔▒` ╓▄▓████████████████████████████████████████⌐
╚╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╣▓ ▄▓████████████████████████████████████████████
▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ▄██████████████████████████████████████████████⌐
╣╬╬╬╬╬╬╬╬╬╬╬╬╬╛ ▄███████████████████████████████████████████████▌
└╣╬╬╬╬╬╬╬╬╬╬╬▓ ▄███████████████████████████████████████████████▌
└▓╬╬╬╬╬╬╬╬╬╬Γ ]███████████████████████████████████████████████▀
╣╬╬╬╬╬╬╬╬╬⌐ ╫████████████████████████████████▀▀▀▀▀▓████████╜
╙╬╬╬╬╬╬╬╬⌐ ╟███████████████████████████▀╙ ,▄▓▓▓▓▓████▓
╫╬╬╬╬╬╬b ████████████████████████▀` ,Φ▀▀█████████╙
╫╬╬╬╬▌╟ ██████████████████▀╓▀─ ▄▓█████████▀
╚╣╬▓╣▓ └▀████████████▀` ╓▓█████████▓╙
╙╝╬╬▓ .▄▄▓█▀▀▀` ▄▓█████████▀
╙▀▓▄ ƒ,▓███████▀▀
" ╓▓█▓█████▀▀└
╓▄▓████▀▀╙└
██████╗██╗ ██╗██╗ ██████╗ █████╗ ███████╗████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ ██████╗ ██╗ ██╗ ██╗██╗███╗ ██╗ ██████╗██╗ ██╗
██╔════╝██║ ██║██║ ██╔════╝ ██╔══██╗██╔════╝╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║ ██╔══██╗╚██╗ ██╔╝ ███║██║████╗ ██║██╔════╝██║ ██║
██║ ███████║██║ ██║ ███╗███████║███████╗ ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║ ██████╔╝ ╚████╔╝ ╚██║██║██╔██╗ ██║██║ ███████║
██║ ██╔══██║██║ ██║ ██║██╔══██║╚════██║ ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║ ██╔══██╗ ╚██╔╝ ██║██║██║╚██╗██║██║ ██╔══██║
╚██████╗██║ ██║██║ ╚██████╔╝██║ ██║███████║ ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║ ██████╔╝ ██║ ██║██║██║ ╚████║╚██████╗██║ ██║
╚═════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝
Copyright by 1inch Corporation
https://1inch.exchange
---
Deployer wallet address:
0x7E1E3334130355799F833ffec2D731BCa3E68aF6
Signed raw transaction for chainId 1:
0xf90d7f808506fc23ac00830bd0fa8080b90d2c608060405234801561001057600080fd5b50610d0c806100206000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c806370a08231116100a2578063a9059cbb11610071578063a9059cbb14610305578063b0ac19a014610331578063d89135cd1461036a578063d8ccd0f314610372578063dd62ed3e1461038f5761010b565b806370a08231146102b057806395d89b41146102d6578063a0712d68146102de578063a2309ff8146102fd5761010b565b806323b872dd116100de57806323b872dd14610213578063313ce567146102495780635f2e2b45146102675780636366b936146102935761010b565b806306fdde0314610110578063079d229f1461018d578063095ea7b3146101cb57806318160ddd1461020b575b600080fd5b6101186103bd565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561015257818101518382015260200161013a565b50505050905090810190601f16801561017f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101b9600480360360408110156101a357600080fd5b506001600160a01b0381351690602001356103ee565b60408051918252519081900360200190f35b6101f7600480360360408110156101e157600080fd5b506001600160a01b03813516906020013561041f565b604080519115158252519081900360200190f35b6101b9610435565b6101f76004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610453565b6102516104c2565b6040805160ff9092168252519081900360200190f35b6101b96004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356104c7565b6101b9600480360360208110156102a957600080fd5b50356104e2565b6101b9600480360360208110156102c657600080fd5b50356001600160a01b03166104ff565b61011861051a565b6102fb600480360360208110156102f457600080fd5b5035610539565b005b6101b961070d565b6101f76004803603604081101561031b57600080fd5b506001600160a01b038135169060200135610713565b61034e6004803603602081101561034757600080fd5b5035610720565b604080516001600160a01b039092168252519081900360200190f35b6101b961078b565b6101b96004803603602081101561038857600080fd5b5035610791565b6101b9600480360360408110156103a557600080fd5b506001600160a01b03813581169160200135166107aa565b60405180604001604052806015815260200174086d0d2408ec2e6e8ded6cadc40c4f24062d2dcc6d605b1b81525081565b60006104188361041361040985610404886104ff565b6107d5565b61040487336107aa565b6104c7565b9392505050565b600061042c3384846107eb565b50600192915050565b600061044e60035460025461084d90919063ffffffff16565b905090565b600061046084848461088f565b6104b884336104b385604051806060016040528060288152602001610c8b602891396001600160a01b038a166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b6107eb565b5060019392505050565b600081565b60006104d383836109f8565b6104dc82610a59565b50919050565b60006104f96104f483610404336104ff565b610791565b92915050565b6001600160a01b031660009081526020819052604090205490565b6040518060400160405280600381526020016243484960e81b81525081565b6002547f746d4946c0e9f43f4dee607b0ef1fa1c3318585733ff6000526015600bf30000600052602082045b80156106d85781601e600080f55060018201601e600080f55060028201601e600080f55060038201601e600080f55060048201601e600080f55060058201601e600080f55060068201601e600080f55060078201601e600080f55060088201601e600080f55060098201601e600080f550600a8201601e600080f550600b8201601e600080f550600c8201601e600080f550600d8201601e600080f550600e8201601e600080f550600f8201601e600080f55060108201601e600080f55060118201601e600080f55060128201601e600080f55060138201601e600080f55060148201601e600080f55060158201601e600080f55060168201601e600080f55060178201601e600080f55060188201601e600080f55060198201601e600080f550601a8201601e600080f550601b8201601e600080f550601c8201601e600080f550601d8201601e600080f550601e8201601e600080f550601f8201601e600080f5506020919091019060001901610565565b50601f82165b80156106fc5781601e600080f55060019190910190600019016106de565b506107073383610ad1565b60025550565b60025481565b600061042c33848461088f565b604080516001600160f81b03196020808301919091523060601b602183015260358201939093527f3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348605580830191909152825180830390910181526075909101909152805191012090565b60035481565b600061079d3383610b50565b6107a682610a59565b5090565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60008183106107e45781610418565b5090919050565b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600061041883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610961565b6108d281604051806060016040528060268152602001610c65602691396001600160a01b038616600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610907908263ffffffff610be816565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156109f05760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156109b557818101518382015260200161099d565b50505050905090810190601f1680156109e25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b610a028282610b50565b610a5582336104b384604051806060016040528060248152602001610cb3602491396001600160a01b0388166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b5050565b60035460005b82811015610aca57610a72818301610720565b6040516001600160a01b039190911690600081818181865af19150503d8060008114610aba576040519150601f19603f3d011682016040523d82523d6000602084013e610abf565b606091505b505050600101610a5f565b5001600355565b6001600160a01b038216600090815260208190526040902054610afa908263ffffffff610be816565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b610b9381604051806060016040528060228152602001610c43602291396001600160a01b038516600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038316600081815260208181526040808320949094558351858152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35050565b600082820183811015610418576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fdfe45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e6365a2646970667358221220687f814fb4c0b3c6abd66ebdb1f1eabcf69becf92a382c3af453e0b21c3d15b564736f6c6343000608003325a00ed87a047b4e415bd7f8cf7a7ce5a1c204125df1cedc35c7bdcb71bd2a29a35ea02db2490337fa6c425f1b3d74b7b217de8b394adb3f571827629c06dc16364b66
---
*/
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
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 Returns the average of two numbers. The result is rounded towards
* zero.
*/
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: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/ChiToken.sol
pragma solidity ^0.6.0;
abstract contract ERC20WithoutTotalSupply is IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _mint(address account, uint256 amount) internal {
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
emit Transfer(account, address(0), amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ChiToken is IERC20, ERC20WithoutTotalSupply {
string constant public name = "Chi Gastoken by 1inch";
string constant public symbol = "CHI";
uint8 constant public decimals = 0;
uint256 public totalMinted;
uint256 public totalBurned;
function totalSupply() public view override returns(uint256) {
return totalMinted.sub(totalBurned);
}
function mint(uint256 value) public {
uint256 offset = totalMinted;
assembly {
mstore(0, 0x746d4946c0e9F43F4Dee607b0eF1fA1c3318585733ff6000526015600bf30000)
for {let i := div(value, 32)} i {i := sub(i, 1)} {
pop(create2(0, 0, 30, add(offset, 0))) pop(create2(0, 0, 30, add(offset, 1)))
pop(create2(0, 0, 30, add(offset, 2))) pop(create2(0, 0, 30, add(offset, 3)))
pop(create2(0, 0, 30, add(offset, 4))) pop(create2(0, 0, 30, add(offset, 5)))
pop(create2(0, 0, 30, add(offset, 6))) pop(create2(0, 0, 30, add(offset, 7)))
pop(create2(0, 0, 30, add(offset, 8))) pop(create2(0, 0, 30, add(offset, 9)))
pop(create2(0, 0, 30, add(offset, 10))) pop(create2(0, 0, 30, add(offset, 11)))
pop(create2(0, 0, 30, add(offset, 12))) pop(create2(0, 0, 30, add(offset, 13)))
pop(create2(0, 0, 30, add(offset, 14))) pop(create2(0, 0, 30, add(offset, 15)))
pop(create2(0, 0, 30, add(offset, 16))) pop(create2(0, 0, 30, add(offset, 17)))
pop(create2(0, 0, 30, add(offset, 18))) pop(create2(0, 0, 30, add(offset, 19)))
pop(create2(0, 0, 30, add(offset, 20))) pop(create2(0, 0, 30, add(offset, 21)))
pop(create2(0, 0, 30, add(offset, 22))) pop(create2(0, 0, 30, add(offset, 23)))
pop(create2(0, 0, 30, add(offset, 24))) pop(create2(0, 0, 30, add(offset, 25)))
pop(create2(0, 0, 30, add(offset, 26))) pop(create2(0, 0, 30, add(offset, 27)))
pop(create2(0, 0, 30, add(offset, 28))) pop(create2(0, 0, 30, add(offset, 29)))
pop(create2(0, 0, 30, add(offset, 30))) pop(create2(0, 0, 30, add(offset, 31)))
offset := add(offset, 32)
}
for {let i := and(value, 0x1F)} i {i := sub(i, 1)} {
pop(create2(0, 0, 30, offset))
offset := add(offset, 1)
}
}
_mint(msg.sender, value);
totalMinted = offset;
}
function computeAddress2(uint256 salt) public view returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), address(this), salt, bytes32(0x3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348))
);
return address(uint256(_data));
}
function _destroyChildren(uint256 value) internal {
uint256 _totalBurned = totalBurned;
for (uint256 i = 0; i < value; i++) {
computeAddress2(_totalBurned + i).call("");
}
totalBurned = _totalBurned + value;
}
function free(uint256 value) public returns (uint256) {
_burn(msg.sender, value);
_destroyChildren(value);
return value;
}
function freeUpTo(uint256 value) public returns (uint256) {
return free(Math.min(value, balanceOf(msg.sender)));
}
function freeFrom(address from, uint256 value) public returns (uint256) {
_burnFrom(from, value);
_destroyChildren(value);
return value;
}
function freeFromUpTo(address from, uint256 value) public returns (uint256) {
return freeFrom(from, Math.min(Math.min(value, balanceOf(from)), allowance(from, msg.sender)));
}
}File 8 of 14: GasToken2
pragma solidity ^0.4.10;
contract GasToken2 {
//////////////////////////////////////////////////////////////////////////
// RLP.sol
// Due to some unexplained bug, we get a slightly different bytecode if
// we use an import, and are then unable to verify the code in Etherscan
//////////////////////////////////////////////////////////////////////////
uint256 constant ADDRESS_BYTES = 20;
uint256 constant MAX_SINGLE_BYTE = 128;
uint256 constant MAX_NONCE = 256**9 - 1;
// count number of bytes required to represent an unsigned integer
function count_bytes(uint256 n) constant internal returns (uint256 c) {
uint i = 0;
uint mask = 1;
while (n >= mask) {
i += 1;
mask *= 256;
}
return i;
}
function mk_contract_address(address a, uint256 n) constant internal returns (address rlp) {
/*
* make sure the RLP encoding fits in one word:
* total_length 1 byte
* address_length 1 byte
* address 20 bytes
* nonce_length 1 byte (or 0)
* nonce 1-9 bytes
* ==========
* 24-32 bytes
*/
require(n <= MAX_NONCE);
// number of bytes required to write down the nonce
uint256 nonce_bytes;
// length in bytes of the RLP encoding of the nonce
uint256 nonce_rlp_len;
if (0 < n && n < MAX_SINGLE_BYTE) {
// nonce fits in a single byte
// RLP(nonce) = nonce
nonce_bytes = 1;
nonce_rlp_len = 1;
} else {
// RLP(nonce) = [num_bytes_in_nonce nonce]
nonce_bytes = count_bytes(n);
nonce_rlp_len = nonce_bytes + 1;
}
// [address_length(1) address(20) nonce_length(0 or 1) nonce(1-9)]
uint256 tot_bytes = 1 + ADDRESS_BYTES + nonce_rlp_len;
// concatenate all parts of the RLP encoding in the leading bytes of
// one 32-byte word
uint256 word = ((192 + tot_bytes) * 256**31) +
((128 + ADDRESS_BYTES) * 256**30) +
(uint256(a) * 256**10);
if (0 < n && n < MAX_SINGLE_BYTE) {
word += n * 256**9;
} else {
word += (128 + nonce_bytes) * 256**9;
word += n * 256**(9 - nonce_bytes);
}
uint256 hash;
assembly {
let mem_start := mload(0x40) // get a pointer to free memory
mstore(0x40, add(mem_start, 0x20)) // update the pointer
mstore(mem_start, word) // store the rlp encoding
hash := sha3(mem_start,
add(tot_bytes, 1)) // hash the rlp encoding
}
// interpret hash as address (20 least significant bytes)
return address(hash);
}
//////////////////////////////////////////////////////////////////////////
// Generic ERC20
//////////////////////////////////////////////////////////////////////////
// owner -> amount
mapping(address => uint256) s_balances;
// owner -> spender -> max amount
mapping(address => mapping(address => uint256)) s_allowances;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// Spec: Get the account balance of another account with address `owner`
function balanceOf(address owner) public constant returns (uint256 balance) {
return s_balances[owner];
}
function internalTransfer(address from, address to, uint256 value) internal returns (bool success) {
if (value <= s_balances[from]) {
s_balances[from] -= value;
s_balances[to] += value;
Transfer(from, to, value);
return true;
} else {
return false;
}
}
// Spec: Send `value` amount of tokens to address `to`
function transfer(address to, uint256 value) public returns (bool success) {
address from = msg.sender;
return internalTransfer(from, to, value);
}
// Spec: Send `value` amount of tokens from address `from` to address `to`
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
address spender = msg.sender;
if(value <= s_allowances[from][spender] && internalTransfer(from, to, value)) {
s_allowances[from][spender] -= value;
return true;
} else {
return false;
}
}
// Spec: Allow `spender` to withdraw from your account, multiple times, up
// to the `value` amount. If this function is called again it overwrites the
// current allowance with `value`.
function approve(address spender, uint256 value) public returns (bool success) {
address owner = msg.sender;
if (value != 0 && s_allowances[owner][spender] != 0) {
return false;
}
s_allowances[owner][spender] = value;
Approval(owner, spender, value);
return true;
}
// Spec: Returns the `amount` which `spender` is still allowed to withdraw
// from `owner`.
// What if the allowance is higher than the balance of the `owner`?
// Callers should be careful to use min(allowance, balanceOf) to make sure
// that the allowance is actually present in the account!
function allowance(address owner, address spender) public constant returns (uint256 remaining) {
return s_allowances[owner][spender];
}
//////////////////////////////////////////////////////////////////////////
// GasToken specifics
//////////////////////////////////////////////////////////////////////////
uint8 constant public decimals = 2;
string constant public name = "Gastoken.io";
string constant public symbol = "GST2";
// We build a queue of nonces at which child contracts are stored. s_head is
// the nonce at the head of the queue, s_tail is the nonce behind the tail
// of the queue. The queue grows at the head and shrinks from the tail.
// Note that when and only when a contract CREATEs another contract, the
// creating contract's nonce is incremented.
// The first child contract is created with nonce == 1, the second child
// contract is created with nonce == 2, and so on...
// For example, if there are child contracts at nonces [2,3,4],
// then s_head == 4 and s_tail == 1. If there are no child contracts,
// s_head == s_tail.
uint256 s_head;
uint256 s_tail;
// totalSupply gives the number of tokens currently in existence
// Each token corresponds to one child contract that can be SELFDESTRUCTed
// for a gas refund.
function totalSupply() public constant returns (uint256 supply) {
return s_head - s_tail;
}
// Creates a child contract that can only be destroyed by this contract.
function makeChild() internal returns (address addr) {
assembly {
// EVM assembler of runtime portion of child contract:
// ;; Pseudocode: if (msg.sender != 0x0000000000b3f879cb30fe243b4dfee438691c04) { throw; }
// ;; suicide(msg.sender)
// PUSH15 0xb3f879cb30fe243b4dfee438691c04 ;; hardcoded address of this contract
// CALLER
// XOR
// PC
// JUMPI
// CALLER
// SELFDESTRUCT
// Or in binary: 6eb3f879cb30fe243b4dfee438691c043318585733ff
// Since the binary is so short (22 bytes), we can get away
// with a very simple initcode:
// PUSH22 0x6eb3f879cb30fe243b4dfee438691c043318585733ff
// PUSH1 0
// MSTORE ;; at this point, memory locations mem[10] through
// ;; mem[31] contain the runtime portion of the child
// ;; contract. all that's left to do is to RETURN this
// ;; chunk of memory.
// PUSH1 22 ;; length
// PUSH1 10 ;; offset
// RETURN
// Or in binary: 756eb3f879cb30fe243b4dfee438691c043318585733ff6000526016600af3
// Almost done! All we have to do is put this short (31 bytes) blob into
// memory and call CREATE with the appropriate offsets.
let solidity_free_mem_ptr := mload(0x40)
mstore(solidity_free_mem_ptr, 0x00756eb3f879cb30fe243b4dfee438691c043318585733ff6000526016600af3)
addr := create(0, add(solidity_free_mem_ptr, 1), 31)
}
}
// Mints `value` new sub-tokens (e.g. cents, pennies, ...) by creating `value`
// new child contracts. The minted tokens are owned by the caller of this
// function.
function mint(uint256 value) public {
for (uint256 i = 0; i < value; i++) {
makeChild();
}
s_head += value;
s_balances[msg.sender] += value;
}
// Destroys `value` child contracts and updates s_tail.
//
// This function is affected by an issue in solc: https://github.com/ethereum/solidity/issues/2999
// The `mk_contract_address(this, i).call();` doesn't forward all available gas, but only GAS - 25710.
// As a result, when this line is executed with e.g. 30000 gas, the callee will have less than 5000 gas
// available and its SELFDESTRUCT operation will fail leading to no gas refund occurring.
// The remaining ~29000 gas left after the call is enough to update s_tail and the caller's balance.
// Hence tokens will have been destroyed without a commensurate gas refund.
// Fortunately, there is a simple workaround:
// Whenever you call free, freeUpTo, freeFrom, or freeUpToFrom, ensure that you pass at least
// 25710 + `value` * (1148 + 5722 + 150) gas. (It won't all be used)
function destroyChildren(uint256 value) internal {
uint256 tail = s_tail;
// tail points to slot behind the last contract in the queue
for (uint256 i = tail + 1; i <= tail + value; i++) {
mk_contract_address(this, i).call();
}
s_tail = tail + value;
}
// Frees `value` sub-tokens (e.g. cents, pennies, ...) belonging to the
// caller of this function by destroying `value` child contracts, which
// will trigger a partial gas refund.
// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
// when calling this function. For details, see the comment above `destroyChilden`.
function free(uint256 value) public returns (bool success) {
uint256 from_balance = s_balances[msg.sender];
if (value > from_balance) {
return false;
}
destroyChildren(value);
s_balances[msg.sender] = from_balance - value;
return true;
}
// Frees up to `value` sub-tokens. Returns how many tokens were freed.
// Otherwise, identical to free.
// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
// when calling this function. For details, see the comment above `destroyChilden`.
function freeUpTo(uint256 value) public returns (uint256 freed) {
uint256 from_balance = s_balances[msg.sender];
if (value > from_balance) {
value = from_balance;
}
destroyChildren(value);
s_balances[msg.sender] = from_balance - value;
return value;
}
// Frees `value` sub-tokens owned by address `from`. Requires that `msg.sender`
// has been approved by `from`.
// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
// when calling this function. For details, see the comment above `destroyChilden`.
function freeFrom(address from, uint256 value) public returns (bool success) {
address spender = msg.sender;
uint256 from_balance = s_balances[from];
if (value > from_balance) {
return false;
}
mapping(address => uint256) from_allowances = s_allowances[from];
uint256 spender_allowance = from_allowances[spender];
if (value > spender_allowance) {
return false;
}
destroyChildren(value);
s_balances[from] = from_balance - value;
from_allowances[spender] = spender_allowance - value;
return true;
}
// Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed.
// Otherwise, identical to `freeFrom`.
// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
// when calling this function. For details, see the comment above `destroyChilden`.
function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) {
address spender = msg.sender;
uint256 from_balance = s_balances[from];
if (value > from_balance) {
value = from_balance;
}
mapping(address => uint256) from_allowances = s_allowances[from];
uint256 spender_allowance = from_allowances[spender];
if (value > spender_allowance) {
value = spender_allowance;
}
destroyChildren(value);
s_balances[from] = from_balance - value;
from_allowances[spender] = spender_allowance - value;
return value;
}
}File 9 of 14: MooniFactory
/*
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNXK0OxdoollccccclodkOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0kdlc;'.. .,:loxkk0KXNWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNKkoc,.. .':ox0XNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOd:'. .;lxKNWMMMMMMMMMMMMMMMWWNNNNNNNNWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo:. .,lkXWMMMMMMMMMWXKOxddol:;;,''.....'',,;:cldxO0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXxc' .;d0NMMMMMMMWXOxl:,.. ..,:ldOKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXx:. .;dKWMMMMMWN0dc,. .,cdOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNkc. 'l0NMMMMMN0d:'. .:d0NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMW0o' .;xXMMMMMNOo,. .....''',,'''.... .'lkXWMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMNOc. .:kNMMMMW0o, ..,:loxk0KKXXNNNWWWNNNNXKK0kxol:,.. .cONMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMNk;. .;ONMMMMXx;. .,cdkKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNKOdc;. ,oKWMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMNk; ,kNMMMW0l. ':dOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOd:' .cOWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMWO: .dXMMMW0c. .;oONWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo;. .:ONMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMWKc. :0WMMWKl. .;dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNWMMMMMMMMMMWKx:. .:OWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMNx. .dNMMMXd. ,o0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0kxOXWMMMMMMMMWKd;. .cKWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMW0: ,OWMMWO, .:kNMMMMMMMMMMMMMMMMMMMMMMWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMWXxc,:d0NMMMMMMMMNOc. .xNMMMMMMMMMMMMMM
MMMMMMMMMMMMMNx. :KMMMXo..c0WMMMMMMMMMMMMMMMMMMMMXxl:;,;;:codkKNMMMMMMMMMMMMMMMMMMMMMMNk;..,o0WMMMMMMMWKo. :KMMMMMMMMMMMMM
MMMMMMMMMMMMXl. cXMMW0:.c0WMMMMMMMMMMMMWWNNXXXNNWXd'..;;'.. .,lkNMMW00NMMMMMMMMMMMMMMMNk; .;dKWMMMMMMWKo. 'kWMMMMMMMMMMM
MMMMMMMMMMMK: cXMMWk;;OWMMMMMMMMMN0xoc;,'.....';cll'.oKNX0xol, ,xXNc.,xXMMMMMMMMMMMMMMMNx' .l0WMMMMMMWKl. .dNMMMMMMMMMM
MMMMMMMMMM0; cXMMWk:dXMMMMMMMMW0o,. ..,:clllllcc:;,..;0WMMMMNO:. ;Ol. ;0MMMMMMMMMMMMMMMMXl. .:OWMMMMMMWO; .lNMMMMMMMMM
MMMMMMMMM0, ;KMMWklkNWMMMMMMMKl. .';coxOXWMMMMWNKOdxKWMMMMMWk, .:l: ,0MMMMMMMMMMMMMMMMWO, .c0WMMMMMMXo. lXMMMMMMMM
MMMMMMMM0, '0MMNx,''lXMMMMMWk' .,cdxkkkxdxxOKXWMMMMMMWNXNMMMMMM0, .kK; cNMMMMMMN0XMMMMMMMMKc .oXMMMMMMWO, lNMMMMMMM
MMMMMMM0; .xWMKc. . .kWMMMNd. .l0NMMMMMMMMMMWNXNWMMMMMMMWNNWMMMMMk. 'OWd. .OMMMMXx:oXMMMMMMMMMNo. ,kWMMMMMMK: .dWMMMMMM
MMMMMMX: cXM0; .l0o..:ool, .lKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMX; ;XMO. .dWWKo'.:KMMMMMMMMMMMWx. .oXMMMMMMXc .kWMMMMM
MMMMMNl .OMX: .oNMWOc'...':dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc.dWMO. lOl. ,0MMMMMMMMMMMMMWx. :KMMMMMMXl ;KMMMMM
MMMMWx. lNMx. ;XMMMMMNXKXNWMWNWMMMMMMMMMMMMMMMXO0WMMMMMMMMMMMMMMMK::XMWx. ...'.'OMMMMMMMMMMMMMMMWd. ;0MMMMMMXc oWMMMM
MMMMK, .kMNl cNMMMMMMMWNX0kxONMMMMMMMMMMMMMMWd..,cok0NWMMMMMMMMM0xKMMX; .cd;'kWMMMMMMMMMMMMMMMMNo ,0MMMMMMK: '0MMMM
MMMWo .cl:. .,ooolllllc::ld0WMMMMMMMMMMMMMMMNl .':oOXNMMMMMWMMWO: ;d00:.xWMMMMMMMMMMMMMMMMMMX: ;KMMMMMM0' oWMMM
MMM0' .':ok0KKK0OkxxkOKNWMMMMMMMMMMMMMMMMMMWo ..;OWMMMMWO:. ,OWK:.dWMMMMMMMMMMMMMMMMMMMMO' :XMMMMMWd. ,KMMM
MMWo .l0NWMMMMMMMMMMMMMMMMMMMMMMMMWXKWMMMMW0o' .kWMWO:. .cOOOO:.oNMMMMMMMMMNXWMMMMMMMMMWo .oWMMMMMX: .kMMM
MMK, .OMMMMMMMMMMMMMMMMMMMMMMMMN0d:.cXMMMKc. .ok:. ..;KMMX:.lNMMMMMMMMMWxlKMMMMMMMMMM0, 'OMMMMMWk. oWMM
MMx. 'OXXNMMMMMMMMMMMMMMMMMWXkl,. lWMWO' ,O0dd0Kc .kMMMMMMMMMWk' cXMMMMMMMMMWl lNMMMMMX; cNMM
MNl .dOKNMMMMMMMMMMMMMMWKxc. lWM0, 'xXWN0: ;0MMMWN0xl,. 'cdOXWMMMMMk. 'OMMMMMWd. ;XMM
MX; ;XMMMMMMMMNOkXMMWKx;. ,KWo .:c, ;KMMWN0ko;. 'cdOXWMMMMMK, dWMMMMMO. ,KMM
M0' ,KMMMMXKN0:.oWW0c. ;d; lNMMMMMMWO'.dNMMMMMMMMMMNc :XMMMMMK, ;KMM
MO. '0MMM0lkO, 'ONd. .oNMMMMMMWkdNMMMMMMMMMMMWo ,KMMMMMX: ;XMM
Mk. .OMM0,,x; ;Ol ..',. ;KMMMMMMMNNMMMMMMMMMMMMWo '0MMMMMNc cNMM
Mx. .dW0, ,:. ,c. .:0Xk:. lNMMMMMMMMMMMMMMMMMMMMMWo .OMMMMMNc oWMM
Mk. c0: .. . .,xOd0NO; '0MMMMMMMMMMMMMWWMMMMMMMWo .OMMMMMN: .kMMM
Mk. .:. .,. .cx: .lKXl lWMMMMMMMMMMMWNxlONMMMMMNc '0MMMMMX; ;XMMM
M0' .:c. .. .,:;,,l0Xl .xMMMMMMMMMMMWNk,.:ONMMMMX; ;XMMMMM0' .dWMMM
MK; 'dl. .....''',:k0d;. oWMMMMMMMMMMMMWOo0MMMMMMO. oWMMMMMx. ,KMMMM
MNc :kl. ...... ,c;. :XMMMMMMMMMMMMMWWWMMMMMWo .kMMMMMNc .dWMMMM
MWd. c0l. .OMMMMMMMMMMMMMMMMMMMMMK; :XMMMMMO' :XMMMMM
MM0' :0d. . lNMMMMMMMMMMMMMMMMMMMWd. .kMMMMMNl '0MMMMMM
MMNl '0k. .. 'c. .OMMMMMMMMMMMMMMMMMMM0, lNMMMMMO. .kWMMMMMM
MMMO. .dK; ;0O; :d' ;KMMMMMMMMMMMMMMMMMNl ,KMMMMMX: .xWMMMWXNM
MMMNc ,0d. .OMMNk:. .x0xo, cXMMMMMMMMMMMMMMMWd. 'OMMMMMNo .dWMMMWOkNM
MMMMO' c0; .dWMMMMW0l. ;dooxl. :0WMMMMMMMMMMMMWk. .kWMMMMWx. .xWMMMWxc0MM
MMMMWd. ok. :XMMMMMMMWO, .:dc 'OWMMMMMMMMMMWO' .kWMMMMWk. 'kWMMMNo,dWMM
MMMMMX: cd. .kWMMMMMMMMWk. .. .,cc. :XMMMMMMMMMWk' 'OWMMMMWk. :0MMMMKc.cXMMM
MMMMMM0, .'. :XMMMMMMMMMMNc 'c;ll. .. .OMMMMMMMMWx. :KMMMMMNx. .oNMMMWO, ;KMMMM
MMMMMMWO' .xWMMMMMMMMMMMk:. ,0KOOc .OMMMMMMMNo. .oXMMMMMXo. ;OWMMMXl. 'OMMMMM
MMMMMMMWk. ,0MMMMMMMMMMMMX0: .:d00l. lNMMMMMW0: ;OWMMMMW0: 'xNMMMNk, 'OWMMMMM
MMMMMMMMWx. :XMMMMMNNMMMMMMWk. .',. 'xNMMMMMNx. ,xNMMMMMNx. .oXMMMWO:. 'OWMMMMMM
MMMMMMMMMWk. cNMMMMNdxNMMMMMMWO:. .;xXMMMMMWO: 'dXMMMMMWO; .oKWMMW0c. 'OWMMMMMMM
MMMMMMMMMMWO, cNWNKk:..:kKNWMMMMWKxc'. .,oONMMMMMW0c. .;xXMMMMMWKl..,dXWMMNOc. ;0WMMMMMMMM
MMMMMMMMMMMMK: cNWN0o' 'oONWMMMMMMMWN0dc;''';lxKNMMMMMMW0l. .cONMMMMMWKl'.ckNMMMNk;. cKMMMMMMMMMM
MMMMMMMMMMMMMXo. cNMMMMKccKMMMMMMMMMMMMMMMMWNNNWMMMMMMMMNOc. .:xXWMMMMMWOl;:dKWMMW0o' .dNMMMMMMMMMMM
MMMMMMMMMMMMMMWk' lNMMMMMXXMMMMMMMMMMMMMMMMMMMMMMMMMMMWKx;. .,lkXWMMMMMWXOdoxKWMMWKd;. ;OWMMMMMMMMMMMM
MMMMMMMMMMMMMMMMKl. oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXkc,';lxKNMMMMMMMWX0OOXWMMN0d;. .oXMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMWk; lXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOxdxOXWMMMMMMMMMMMWNWMMWKxl,. .:0WMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMXd' .:ok0NWMMMMMMMMMMMMMMMMMMMMMMMWNWWMMMMMMMMMMMMMMMMWX0xl,. ,kNMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMXo. .':ldOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXKOdc;.. 'xNMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMWKo' .';ccldxO0KXXNWWWWWWWWWNNXKKOkxol:,.. ,xXMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMWXd, ....',,,,,,,,,'.... .;kNMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMNk:. .l0WMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKo,. .:xXWMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo, .;dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo;. .:xKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKxc'. .;oOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xl;. .':oOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOdl;'. ..,cokKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNKOxoc;,... ..';:ldk0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWXK0Okxdollcccc:::cccclloddkO0KXNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
███╗ ███╗ ██████╗ ██████╗ ███╗ ██╗██╗███████╗██╗ ██╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██████╗██╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗
████╗ ████║██╔═══██╗██╔═══██╗████╗ ██║██║██╔════╝██║ ██║██╔══██╗██╔══██╗██╔════╝╚██╗██╔╝██╔════╝██║ ██║██╔══██╗████╗ ██║██╔════╝ ██╔════╝
██╔████╔██║██║ ██║██║ ██║██╔██╗ ██║██║███████╗██║ █╗ ██║███████║██████╔╝█████╗ ╚███╔╝ ██║ ███████║███████║██╔██╗ ██║██║ ███╗█████╗
██║╚██╔╝██║██║ ██║██║ ██║██║╚██╗██║██║╚════██║██║███╗██║██╔══██║██╔═══╝ ██╔══╝ ██╔██╗ ██║ ██╔══██║██╔══██║██║╚██╗██║██║ ██║██╔══╝
██║ ╚═╝ ██║╚██████╔╝╚██████╔╝██║ ╚████║██║███████║╚███╔███╔╝██║ ██║██║██╗ ███████╗██╔╝ ██╗╚██████╗██║ ██║██║ ██║██║ ╚████║╚██████╔╝███████╗
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝
██████╗ ██╗ ██╗ ██╗██╗███╗ ██╗ ██████╗██╗ ██╗
██╔══██╗╚██╗ ██╔╝ ███║██║████╗ ██║██╔════╝██║ ██║
██████╔╝ ╚████╔╝ ╚██║██║██╔██╗ ██║██║ ███████║
██╔══██╗ ╚██╔╝ ██║██║██║╚██╗██║██║ ██╔══██║
██████╔╝ ██║ ██║██║██║ ╚████║╚██████╗██║ ██║
╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝
*/
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/libraries/UniERC20.sol
pragma solidity ^0.6.0;
library UniERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(0));
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(IERC20 token, address payable to, uint256 amount) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount > 0) {
if (isETH(token)) {
require(msg.value >= amount, "UniERC20: not enough value");
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
}
function uniSymbol(IERC20 token) internal view returns(string memory) {
if (isETH(token)) {
return "ETH";
}
(bool success, bytes memory data) = address(token).staticcall{ gas: 20000 }(
abi.encodeWithSignature("symbol()")
);
if (!success) {
(success, data) = address(token).staticcall{ gas: 20000 }(
abi.encodeWithSignature("SYMBOL()")
);
}
if (success && data.length >= 96) {
(uint256 offset, uint256 len) = abi.decode(data, (uint256, uint256));
if (offset == 0x20 && len > 0 && len <= 256) {
return string(abi.decode(data, (bytes)));
}
}
if (success && data.length == 32) {
uint len = 0;
while (len < data.length && data[len] >= 0x20 && data[len] <= 0x7E) {
len++;
}
if (len > 0) {
bytes memory result = new bytes(len);
for (uint i = 0; i < len; i++) {
result[i] = data[i];
}
return string(result);
}
}
return _toHex(address(token));
}
function _toHex(address account) private pure returns(string memory) {
return _toHex(abi.encodePacked(account));
}
function _toHex(bytes memory data) private pure returns(string memory) {
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
uint j = 2;
for (uint i = 0; i < data.length; i++) {
uint a = uint8(data[i]) >> 4;
uint b = uint8(data[i]) & 0x0f;
str[j++] = byte(uint8(a + 48 + (a/10)*39));
str[j++] = byte(uint8(b + 48 + (b/10)*39));
}
return string(str);
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @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() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
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 Returns the average of two numbers. The result is rounded towards
* zero.
*/
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: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/libraries/Sqrt.sol
pragma solidity ^0.6.0;
library Sqrt {
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256) {
if (y > 3) {
uint256 z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
return z;
} else if (y != 0) {
return 1;
} else {
return 0;
}
}
}
// File: contracts/Mooniswap.sol
pragma solidity ^0.6.0;
interface IFactory {
function fee() external view returns(uint256);
}
library VirtualBalance {
using SafeMath for uint256;
struct Data {
uint216 balance;
uint40 time;
}
uint256 public constant DECAY_PERIOD = 5 minutes;
function set(VirtualBalance.Data storage self, uint256 balance) internal {
self.balance = uint216(balance);
self.time = uint40(block.timestamp);
}
function update(VirtualBalance.Data storage self, uint256 realBalance) internal {
set(self, current(self, realBalance));
}
function scale(VirtualBalance.Data storage self, uint256 realBalance, uint256 num, uint256 denom) internal {
set(self, current(self, realBalance).mul(num).add(denom.sub(1)).div(denom));
}
function current(VirtualBalance.Data memory self, uint256 realBalance) internal view returns(uint256) {
uint256 timePassed = Math.min(DECAY_PERIOD, block.timestamp.sub(self.time));
uint256 timeRemain = DECAY_PERIOD.sub(timePassed);
return uint256(self.balance).mul(timeRemain).add(
realBalance.mul(timePassed)
).div(DECAY_PERIOD);
}
}
contract Mooniswap is ERC20, ReentrancyGuard, Ownable {
using Sqrt for uint256;
using SafeMath for uint256;
using UniERC20 for IERC20;
using VirtualBalance for VirtualBalance.Data;
struct Balances {
uint256 src;
uint256 dst;
}
struct SwapVolumes {
uint128 confirmed;
uint128 result;
}
event Deposited(
address indexed account,
uint256 amount
);
event Withdrawn(
address indexed account,
uint256 amount
);
event Swapped(
address indexed account,
address indexed src,
address indexed dst,
uint256 amount,
uint256 result,
uint256 srcBalance,
uint256 dstBalance,
uint256 totalSupply,
address referral
);
uint256 public constant REFERRAL_SHARE = 20; // 1/share = 5% of LPs revenue
uint256 public constant BASE_SUPPLY = 1000; // Total supply on first deposit
uint256 public constant FEE_DENOMINATOR = 1e18;
IFactory public factory;
IERC20[] public tokens;
mapping(IERC20 => bool) public isToken;
mapping(IERC20 => SwapVolumes) public volumes;
mapping(IERC20 => VirtualBalance.Data) public virtualBalancesForAddition;
mapping(IERC20 => VirtualBalance.Data) public virtualBalancesForRemoval;
constructor(IERC20[] memory assets, string memory name, string memory symbol) public ERC20(name, symbol) {
require(bytes(name).length > 0, "Mooniswap: name is empty");
require(bytes(symbol).length > 0, "Mooniswap: symbol is empty");
require(assets.length == 2, "Mooniswap: only 2 tokens allowed");
factory = IFactory(msg.sender);
tokens = assets;
for (uint i = 0; i < assets.length; i++) {
require(!isToken[assets[i]], "Mooniswap: duplicate tokens");
isToken[assets[i]] = true;
}
}
function fee() public view returns(uint256) {
return factory.fee();
}
function getTokens() external view returns(IERC20[] memory) {
return tokens;
}
function decayPeriod() external pure returns(uint256) {
return VirtualBalance.DECAY_PERIOD;
}
function getBalanceForAddition(IERC20 token) public view returns(uint256) {
uint256 balance = token.uniBalanceOf(address(this));
return Math.max(virtualBalancesForAddition[token].current(balance), balance);
}
function getBalanceForRemoval(IERC20 token) public view returns(uint256) {
uint256 balance = token.uniBalanceOf(address(this));
return Math.min(virtualBalancesForRemoval[token].current(balance), balance);
}
function getReturn(IERC20 src, IERC20 dst, uint256 amount) external view returns(uint256) {
return _getReturn(src, dst, amount, getBalanceForAddition(src), getBalanceForRemoval(dst));
}
function deposit(uint256[] calldata amounts, uint256[] calldata minAmounts) external payable nonReentrant returns(uint256 fairSupply) {
IERC20[] memory _tokens = tokens;
require(amounts.length == _tokens.length, "Mooniswap: wrong amounts length");
require(msg.value == (_tokens[0].isETH() ? amounts[0] : (_tokens[1].isETH() ? amounts[1] : 0)), "Mooniswap: wrong value usage");
uint256[] memory realBalances = new uint256[](amounts.length);
for (uint i = 0; i < realBalances.length; i++) {
realBalances[i] = _tokens[i].uniBalanceOf(address(this)).sub(_tokens[i].isETH() ? msg.value : 0);
}
uint256 totalSupply = totalSupply();
if (totalSupply == 0) {
fairSupply = BASE_SUPPLY.mul(99);
_mint(address(this), BASE_SUPPLY); // Donate up to 1%
// Use the greatest token amount but not less than 99k for the initial supply
for (uint i = 0; i < amounts.length; i++) {
fairSupply = Math.max(fairSupply, amounts[i]);
}
}
else {
// Pre-compute fair supply
fairSupply = type(uint256).max;
for (uint i = 0; i < amounts.length; i++) {
fairSupply = Math.min(fairSupply, totalSupply.mul(amounts[i]).div(realBalances[i]));
}
}
uint256 fairSupplyCached = fairSupply;
for (uint i = 0; i < amounts.length; i++) {
require(amounts[i] > 0, "Mooniswap: amount is zero");
uint256 amount = (totalSupply == 0) ? amounts[i] :
realBalances[i].mul(fairSupplyCached).add(totalSupply - 1).div(totalSupply);
require(amount >= minAmounts[i], "Mooniswap: minAmount not reached");
_tokens[i].uniTransferFromSenderToThis(amount);
if (totalSupply > 0) {
uint256 confirmed = _tokens[i].uniBalanceOf(address(this)).sub(realBalances[i]);
fairSupply = Math.min(fairSupply, totalSupply.mul(confirmed).div(realBalances[i]));
}
}
if (totalSupply > 0) {
for (uint i = 0; i < amounts.length; i++) {
virtualBalancesForRemoval[_tokens[i]].scale(realBalances[i], totalSupply.add(fairSupply), totalSupply);
virtualBalancesForAddition[_tokens[i]].scale(realBalances[i], totalSupply.add(fairSupply), totalSupply);
}
}
require(fairSupply > 0, "Mooniswap: result is not enough");
_mint(msg.sender, fairSupply);
emit Deposited(msg.sender, fairSupply);
}
function withdraw(uint256 amount, uint256[] memory minReturns) external nonReentrant {
uint256 totalSupply = totalSupply();
_burn(msg.sender, amount);
for (uint i = 0; i < tokens.length; i++) {
IERC20 token = tokens[i];
uint256 preBalance = token.uniBalanceOf(address(this));
uint256 value = preBalance.mul(amount).div(totalSupply);
token.uniTransfer(msg.sender, value);
require(i >= minReturns.length || value >= minReturns[i], "Mooniswap: result is not enough");
virtualBalancesForAddition[token].scale(preBalance, totalSupply.sub(amount), totalSupply);
virtualBalancesForRemoval[token].scale(preBalance, totalSupply.sub(amount), totalSupply);
}
emit Withdrawn(msg.sender, amount);
}
function swap(IERC20 src, IERC20 dst, uint256 amount, uint256 minReturn, address referral) external payable nonReentrant returns(uint256 result) {
require(msg.value == (src.isETH() ? amount : 0), "Mooniswap: wrong value usage");
Balances memory balances = Balances({
src: src.uniBalanceOf(address(this)).sub(src.isETH() ? msg.value : 0),
dst: dst.uniBalanceOf(address(this))
});
// catch possible airdrops and external balance changes for deflationary tokens
uint256 srcAdditionBalance = Math.max(virtualBalancesForAddition[src].current(balances.src), balances.src);
uint256 dstRemovalBalance = Math.min(virtualBalancesForRemoval[dst].current(balances.dst), balances.dst);
src.uniTransferFromSenderToThis(amount);
uint256 confirmed = src.uniBalanceOf(address(this)).sub(balances.src);
result = _getReturn(src, dst, confirmed, srcAdditionBalance, dstRemovalBalance);
require(result > 0 && result >= minReturn, "Mooniswap: return is not enough");
dst.uniTransfer(msg.sender, result);
// Update virtual balances to the same direction only at imbalanced state
if (srcAdditionBalance != balances.src) {
virtualBalancesForAddition[src].set(srcAdditionBalance.add(confirmed));
}
if (dstRemovalBalance != balances.dst) {
virtualBalancesForRemoval[dst].set(dstRemovalBalance.sub(result));
}
// Update virtual balances to the opposite direction
virtualBalancesForRemoval[src].update(balances.src);
virtualBalancesForAddition[dst].update(balances.dst);
if (referral != address(0)) {
uint256 invariantRatio = uint256(1e36);
invariantRatio = invariantRatio.mul(balances.src.add(confirmed)).div(balances.src);
invariantRatio = invariantRatio.mul(balances.dst.sub(result)).div(balances.dst);
if (invariantRatio > 1e36) {
// calculate share only if invariant increased
uint256 referralShare = invariantRatio.sqrt().sub(1e18).mul(totalSupply()).div(1e18).div(REFERRAL_SHARE);
if (referralShare > 0) {
_mint(referral, referralShare);
}
}
}
emit Swapped(msg.sender, address(src), address(dst), confirmed, result, balances.src, balances.dst, totalSupply(), referral);
// Overflow of uint128 is desired
volumes[src].confirmed += uint128(confirmed);
volumes[src].result += uint128(result);
}
function rescueFunds(IERC20 token, uint256 amount) external nonReentrant onlyOwner {
uint256[] memory balances = new uint256[](tokens.length);
for (uint i = 0; i < balances.length; i++) {
balances[i] = tokens[i].uniBalanceOf(address(this));
}
token.uniTransfer(msg.sender, amount);
for (uint i = 0; i < balances.length; i++) {
require(tokens[i].uniBalanceOf(address(this)) >= balances[i], "Mooniswap: access denied");
}
require(balanceOf(address(this)) >= BASE_SUPPLY, "Mooniswap: access denied");
}
function _getReturn(IERC20 src, IERC20 dst, uint256 amount, uint256 srcBalance, uint256 dstBalance) internal view returns(uint256) {
if (isToken[src] && isToken[dst] && src != dst && amount > 0) {
uint256 taxedAmount = amount.sub(amount.mul(fee()).div(FEE_DENOMINATOR));
return taxedAmount.mul(dstBalance).div(srcBalance.add(taxedAmount));
}
}
}
// File: contracts/MooniFactory.sol
pragma solidity ^0.6.0;
contract MooniFactory is Ownable {
using UniERC20 for IERC20;
event Deployed(
address indexed mooniswap,
address indexed token1,
address indexed token2
);
uint256 public constant MAX_FEE = 0.003e18; // 0.3%
uint256 public fee;
Mooniswap[] public allPools;
mapping(Mooniswap => bool) public isPool;
mapping(IERC20 => mapping(IERC20 => Mooniswap)) public pools;
function getAllPools() external view returns(Mooniswap[] memory) {
return allPools;
}
function setFee(uint256 newFee) external onlyOwner {
require(newFee <= MAX_FEE, "Factory: fee should be <= 0.3%");
fee = newFee;
}
function deploy(IERC20 tokenA, IERC20 tokenB) public returns(Mooniswap pool) {
require(tokenA != tokenB, "Factory: not support same tokens");
require(pools[tokenA][tokenB] == Mooniswap(0), "Factory: pool already exists");
(IERC20 token1, IERC20 token2) = sortTokens(tokenA, tokenB);
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = token1;
tokens[1] = token2;
string memory symbol1 = token1.uniSymbol();
string memory symbol2 = token2.uniSymbol();
pool = new Mooniswap(
tokens,
string(abi.encodePacked("Mooniswap V1 (", symbol1, "-", symbol2, ")")),
string(abi.encodePacked("MOON-V1-", symbol1, "-", symbol2))
);
pool.transferOwnership(owner());
pools[token1][token2] = pool;
pools[token2][token1] = pool;
allPools.push(pool);
isPool[pool] = true;
emit Deployed(
address(pool),
address(token1),
address(token2)
);
}
function sortTokens(IERC20 tokenA, IERC20 tokenB) public pure returns(IERC20, IERC20) {
if (tokenA < tokenB) {
return (tokenA, tokenB);
}
return (tokenB, tokenA);
}
}File 10 of 14: DmmController
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: @openzeppelin/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/constants/CommonConstants.sol
pragma solidity ^0.5.0;
contract CommonConstants {
uint public constant EXCHANGE_RATE_BASE_RATE = 1e18;
}
// File: contracts/utils/Blacklistable.sol
pragma solidity ^0.5.0;
/**
* @dev Allows accounts to be blacklisted by the owner of the contract.
*
* Taken from USDC's contract for blacklisting certain addresses from owning and interacting with the token.
*/
contract Blacklistable is Ownable {
string public constant BLACKLISTED = "BLACKLISTED";
mapping(address => bool) internal blacklisted;
event Blacklisted(address indexed account);
event UnBlacklisted(address indexed account);
event BlacklisterChanged(address indexed newBlacklister);
/**
* @dev Throws if called by any account other than the creator of this contract
*/
modifier onlyBlacklister() {
require(msg.sender == owner(), "MUST_BE_BLACKLISTER");
_;
}
/**
* @dev Throws if `account` is blacklisted
*
* @param account The address to check
*/
modifier notBlacklisted(address account) {
require(blacklisted[account] == false, BLACKLISTED);
_;
}
/**
* @dev Checks if `account` is blacklisted. Reverts with `BLACKLISTED` if blacklisted.
*/
function checkNotBlacklisted(address account) public view {
require(!blacklisted[account], BLACKLISTED);
}
/**
* @dev Checks if `account` is blacklisted
*
* @param account The address to check
*/
function isBlacklisted(address account) public view returns (bool) {
return blacklisted[account];
}
/**
* @dev Adds `account` to blacklist
*
* @param account The address to blacklist
*/
function blacklist(address account) public onlyBlacklister {
blacklisted[account] = true;
emit Blacklisted(account);
}
/**
* @dev Removes account from blacklist
*
* @param account The address to remove from the blacklist
*/
function unBlacklist(address account) public onlyBlacklister {
blacklisted[account] = false;
emit UnBlacklisted(account);
}
}
// File: contracts/impl/DmmBlacklistable.sol
pragma solidity ^0.5.0;
contract DmmBlacklistable is Blacklistable {
constructor() public {
}
}
// File: contracts/interfaces/IOffChainAssetValuator.sol
pragma solidity ^0.5.0;
interface IOffChainAssetValuator {
event AssetsValueUpdated(uint newAssetsValue);
/**
* @dev Gets the DMM ecosystem's collateral's value from Chainlink's on-chain data feed.
*
* @return The value of the ecosystem's collateral, as a number with 18 decimals
*/
function getOffChainAssetsValue() external view returns (uint);
}
// File: contracts/interfaces/InterestRateInterface.sol
pragma solidity ^0.5.0;
interface InterestRateInterface {
/**
* @dev Returns the current interest rate for the given DMMA and corresponding total supply & active supply
*
* @param dmmTokenId The DMMA whose interest should be retrieved
* @param totalSupply The total supply fot he DMM token
* @param activeSupply The supply that's currently being lent by users
* @return The interest rate in APY, which is a number with 18 decimals
*/
function getInterestRate(uint dmmTokenId, uint totalSupply, uint activeSupply) external view returns (uint);
}
// File: contracts/interfaces/IDmmController.sol
pragma solidity ^0.5.0;
interface IDmmController {
event TotalSupplyIncreased(uint oldTotalSupply, uint newTotalSupply);
event TotalSupplyDecreased(uint oldTotalSupply, uint newTotalSupply);
event AdminDeposit(address indexed sender, uint amount);
event AdminWithdraw(address indexed receiver, uint amount);
function blacklistable() external view returns (Blacklistable);
/**
* @dev Creates a new mToken using the provided data.
*
* @param underlyingToken The token that should be wrapped to create a new DMMA
* @param symbol The symbol of the new DMMA, IE mDAI or mUSDC
* @param name The name of this token, IE `DMM: DAI`
* @param decimals The number of decimals of the underlying token, and therefore the number for this DMMA
* @param minMintAmount The minimum amount that can be minted for any given transaction.
* @param minRedeemAmount The minimum amount that can be redeemed any given transaction.
* @param totalSupply The initial total supply for this market.
*/
function addMarket(
address underlyingToken,
string calldata symbol,
string calldata name,
uint8 decimals,
uint minMintAmount,
uint minRedeemAmount,
uint totalSupply
) external;
/**
* @dev Creates a new mToken using the already-existing token.
*
* @param dmmToken The token that should be added to this controller.
* @param underlyingToken The token that should be wrapped to create a new DMMA.
*/
function addMarketFromExistingDmmToken(
address dmmToken,
address underlyingToken
) external;
/**
* @param newController The new controller who should receive ownership of the provided DMM token IDs.
*/
function transferOwnershipToNewController(
address newController
) external;
/**
* @dev Enables the corresponding DMMA to allow minting new tokens.
*
* @param dmmTokenId The DMMA that should be enabled.
*/
function enableMarket(uint dmmTokenId) external;
/**
* @dev Disables the corresponding DMMA from minting new tokens. This allows the market to close over time, since
* users are only able to redeem tokens.
*
* @param dmmTokenId The DMMA that should be disabled.
*/
function disableMarket(uint dmmTokenId) external;
/**
* @dev Sets a new contract that implements the `InterestRateInterface` interface.
*
* @param newInterestRateInterface The new contract that implements the `InterestRateInterface` interface.
*/
function setInterestRateInterface(address newInterestRateInterface) external;
/**
* @dev Sets a new contract that implements the `IOffChainAssetValuator` interface.
*
* @param newOffChainAssetValuator The new contract that implements the `IOffChainAssetValuator` interface.
*/
function setOffChainAssetValuator(address newOffChainAssetValuator) external;
/**
* @dev Sets a new contract that implements the `IOffChainAssetValuator` interface.
*
* @param newOffChainCurrencyValuator The new contract that implements the `IOffChainAssetValuator` interface.
*/
function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) external;
/**
* @dev Sets a new contract that implements the `UnderlyingTokenValuator` interface
*
* @param newUnderlyingTokenValuator The new contract that implements the `UnderlyingTokenValuator` interface
*/
function setUnderlyingTokenValuator(address newUnderlyingTokenValuator) external;
/**
* @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
* allocated to real-world assets that will be used to pay interest into the DMMA.
*
* @param newMinCollateralization The new min collateralization (with 18 decimals) at which the DMME must be in
* order to add to the total supply of DMM.
*/
function setMinCollateralization(uint newMinCollateralization) external;
/**
* @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
* allocated to real-world assets that will be used to pay interest into the DMMA.
*
* @param newMinReserveRatio The new ratio (with 18 decimals) that is used to enforce a certain percentage of assets
* are kept in each DMMA.
*/
function setMinReserveRatio(uint newMinReserveRatio) external;
/**
* @dev Increases the max supply for the provided `dmmTokenId` by `amount`. This call reverts with
* INSUFFICIENT_COLLATERAL if there isn't enough collateral in the Chainlink contract to cover the controller's
* requirements for minimum collateral.
*/
function increaseTotalSupply(uint dmmTokenId, uint amount) external;
/**
* @dev Increases the max supply for the provided `dmmTokenId` by `amount`.
*/
function decreaseTotalSupply(uint dmmTokenId, uint amount) external;
/**
* @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
* allocated to real-world assets that will be used to pay interest into the DMMA.
*
* @param dmmTokenId The ID of the DMM token whose underlying will be funded.
* @param underlyingAmount The amount underlying the DMM token that will be deposited into the DMMA.
*/
function adminWithdrawFunds(uint dmmTokenId, uint underlyingAmount) external;
/**
* @dev Allows the owners of the DMM Ecosystem to deposit funds into a DMMA. These funds are used to disburse
* interest payments and add more liquidity to the specific market.
*
* @param dmmTokenId The ID of the DMM token whose underlying will be funded.
* @param underlyingAmount The amount underlying the DMM token that will be deposited into the DMMA.
*/
function adminDepositFunds(uint dmmTokenId, uint underlyingAmount) external;
/**
* @dev Gets the collateralization of the system assuming 1-year's worth of interest payments are due by dividing
* the total value of all the collateralized assets plus the value of the underlying tokens in each DMMA by the
* aggregate interest owed (plus the principal), assuming each DMMA was at maximum usage.
*
* @return The 1-year collateralization of the system, as a number with 18 decimals. For example
* `1010000000000000000` is 101% or 1.01.
*/
function getTotalCollateralization() external view returns (uint);
/**
* @dev Gets the current collateralization of the system assuming by dividing the total value of all the
* collateralized assets plus the value of the underlying tokens in each DMMA by the aggregate interest owed
* (plus the principal), using the current usage of each DMMA.
*
* @return The active collateralization of the system, as a number with 18 decimals. For example
* `1010000000000000000` is 101% or 1.01.
*/
function getActiveCollateralization() external view returns (uint);
/**
* @dev Gets the interest rate from the underlying token, IE DAI or USDC.
*
* @return The current interest rate, represented using 18 decimals. Meaning `65000000000000000` is 6.5% APY or
* 0.065.
*/
function getInterestRateByUnderlyingTokenAddress(address underlyingToken) external view returns (uint);
/**
* @dev Gets the interest rate from the DMM token, IE DMM: DAI or DMM: USDC.
*
* @return The current interest rate, represented using 18 decimals. Meaning, `65000000000000000` is 6.5% APY or
* 0.065.
*/
function getInterestRateByDmmTokenId(uint dmmTokenId) external view returns (uint);
/**
* @dev Gets the interest rate from the DMM token, IE DMM: DAI or DMM: USDC.
*
* @return The current interest rate, represented using 18 decimals. Meaning, `65000000000000000` is 6.5% APY or
* 0.065.
*/
function getInterestRateByDmmTokenAddress(address dmmToken) external view returns (uint);
/**
* @dev Gets the exchange rate from the underlying to the DMM token, such that
* `DMM: Token = underlying / exchangeRate`
*
* @return The current exchange rate, represented using 18 decimals. Meaning, `200000000000000000` is 0.2.
*/
function getExchangeRateByUnderlying(address underlyingToken) external view returns (uint);
/**
* @dev Gets the exchange rate from the underlying to the DMM token, such that
* `DMM: Token = underlying / exchangeRate`
*
* @return The current exchange rate, represented using 18 decimals. Meaning, `200000000000000000` is 0.2.
*/
function getExchangeRate(address dmmToken) external view returns (uint);
/**
* @dev Gets the DMM token for the provided underlying token. For example, sending DAI returns DMM: DAI.
*/
function getDmmTokenForUnderlying(address underlyingToken) external view returns (address);
/**
* @dev Gets the underlying token for the provided DMM token. For example, sending DMM: DAI returns DAI.
*/
function getUnderlyingTokenForDmm(address dmmToken) external view returns (address);
/**
* @return True if the market is enabled for this DMMA or false if it is not enabled.
*/
function isMarketEnabledByDmmTokenId(uint dmmTokenId) external view returns (bool);
/**
* @return True if the market is enabled for this DMM token (IE DMM: DAI) or false if it is not enabled.
*/
function isMarketEnabledByDmmTokenAddress(address dmmToken) external view returns (bool);
/**
* @return True if the market is enabled for this underlying token (IE DAI) or false if it is not enabled.
*/
function getTokenIdFromDmmTokenAddress(address dmmTokenAddress) external view returns (uint);
}
// File: contracts/interfaces/IDmmToken.sol
pragma solidity ^0.5.0;
/**
* Basically an interface except, contains the implementation of the type-hashes for offline signature generation.
*
* This contract contains the signatures and documentation for all publicly-implemented functions in the DMM token.
*/
interface IDmmToken {
/*****************
* Events
*/
event Mint(address indexed minter, address indexed recipient, uint amount);
event Redeem(address indexed redeemer, address indexed recipient, uint amount);
event FeeTransfer(address indexed owner, address indexed recipient, uint amount);
event TotalSupplyIncreased(uint oldTotalSupply, uint newTotalSupply);
event TotalSupplyDecreased(uint oldTotalSupply, uint newTotalSupply);
event OffChainRequestValidated(address indexed owner, address indexed feeRecipient, uint nonce, uint expiry, uint feeAmount);
/*****************
* Functions
*/
/**
* @dev The controller that deployed this parent
*/
function controller() external view returns (IDmmController);
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
/**
* @return The min amount that can be minted in a single transaction. This amount corresponds with the number of
* decimals that this token has.
*/
function minMintAmount() external view returns (uint);
/**
* @return The min amount that can be redeemed from DMM to underlying in a single transaction. This amount
* corresponds with the number of decimals that this token has.
*/
function minRedeemAmount() external view returns (uint);
/**
* @dev The amount of DMM that is in circulation (outside of this contract)
*/
function activeSupply() external view returns (uint);
/**
* @dev Attempts to add `amount` to the total supply by issuing the tokens to this contract. This call fires a
* Transfer event from the 0x0 address to this contract.
*/
function increaseTotalSupply(uint amount) external;
/**
* @dev Attempts to remove `amount` from the total supply by destroying those tokens that are held in this
* contract. This call reverts with TOO_MUCH_ACTIVE_SUPPLY if `amount` is not held in this contract.
*/
function decreaseTotalSupply(uint amount) external;
/**
* @dev An admin function that lets the ecosystem's organizers deposit the underlying token around which this DMMA
* wraps to this contract. This is used to replenish liquidity and after interest payouts are made from the
* real-world assets.
*/
function depositUnderlying(uint underlyingAmount) external returns (bool);
/**
* @dev An admin function that lets the ecosystem's organizers withdraw the underlying token around which this DMMA
* wraps from this contract. This is used to withdraw deposited tokens, to be allocated to real-world assets
* that produce income streams and can cover interest payments.
*/
function withdrawUnderlying(uint underlyingAmount) external returns (bool);
/**
* @dev The timestamp at which the exchange rate was last updated.
*/
function exchangeRateLastUpdatedTimestamp() external view returns (uint);
/**
* @dev The timestamp at which the exchange rate was last updated.
*/
function exchangeRateLastUpdatedBlockNumber() external view returns (uint);
/**
* @dev The exchange rate from underlying to DMM. Invert this number to go from DMM to underlying. This number
* has 18 decimals.
*/
function getCurrentExchangeRate() external view returns (uint);
/**
* @dev The current nonce of the provided `owner`. This `owner` should be the signer for any gasless transactions.
*/
function nonceOf(address owner) external view returns (uint);
/**
* @dev Transfers the token around which this DMMA wraps from msg.sender to the DMMA contract. Then, sends the
* corresponding amount of DMM to the msg.sender. Note, this call reverts with INSUFFICIENT_DMM_LIQUIDITY if
* there is not enough DMM available to be minted.
*
* @param amount The amount of underlying to send to this DMMA for conversion to DMM.
* @return The amount of DMM minted.
*/
function mint(uint amount) external returns (uint);
/**
* @dev Transfers the token around which this DMMA wraps from sender to the DMMA contract. Then, sends the
* corresponding amount of DMM to recipient. Note, an allowance must be set for sender for the underlying
* token that is at least of size `amount` / `exchangeRate`. This call reverts with INSUFFICIENT_DMM_LIQUIDITY
* if there is not enough DMM available to be minted. See #MINT_TYPE_HASH. This function gives the `owner` the
* illusion of committing a gasless transaction, allowing a relayer to broadcast the transaction and
* potentially collect a fee for doing so.
*
* @param owner The user that signed the off-chain message.
* @param recipient The address that will receive the newly-minted DMM tokens.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param amount The amount of underlying that should be minted by `owner` and sent to `recipient`.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee. Must be <= `amount`.
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
* @return The amount of DMM minted, minus the fees paid. To get the total amount minted, add the `feeAmount` to
* the returned amount from this function call.
*/
function mintFromGaslessRequest(
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
/**
* @dev Transfers DMM from msg.sender to this DMMA contract. Then, sends the corresponding amount of token around
* which this DMMA wraps to the msg.sender. Note, this call reverts with INSUFFICIENT_UNDERLYING_LIQUIDITY if
* there is not enough DMM available to be redeemed.
*
* @param amount The amount of DMM to be transferred from msg.sender to this DMMA.
* @return The amount of underlying redeemed.
*/
function redeem(uint amount) external returns (uint);
/**
* @dev Transfers DMM from `owner` to the DMMA contract. Then, sends the corresponding amount of token around which
* this DMMA wraps to `recipient`. Note, an allowance must be set for sender for the underlying
* token that is at least of size `amount`. This call reverts with INSUFFICIENT_UNDERLYING_LIQUIDITY
* if there is not enough underlying available to be redeemed. See #REDEEM_TYPE_HASH. This function gives the
* `owner` the illusion of committing a gasless transaction, allowing a relayer to broadcast the transaction
* and potentially collect a fee for doing so.
*
* @param owner The user that signed the off-chain message.
* @param recipient The address that will receive the newly-redeemed DMM tokens.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param amount The amount of DMM that should be redeemed for `owner` and sent to `recipient`.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee. Must be <= `amount`
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
* @return The amount of underlying redeemed.
*/
function redeemFromGaslessRequest(
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
/**
* @dev Sets an allowance for owner with spender using an offline-generated signature. This function allows a
* relayer to send the transaction, giving the owner the illusion of committing a gasless transaction. See
* #PERMIT_TYPEHASH.
*
* @param owner The user that signed the off-chain message.
* @param spender The contract/wallet that can spend DMM tokens on behalf of owner.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param allowed True if the spender can spend funds on behalf of owner or false to revoke this privilege.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee.
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
*/
function permit(
address owner,
address spender,
uint nonce,
uint expiry,
bool allowed,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Transfers DMM from the `owner` to `recipient` using an offline-generated signature. This function allows a
* relayer to send the transaction, giving the owner the illusion of committing a gasless transaction. See
* #TRANSFER_TYPEHASH. This function gives the `owner` the illusion of committing a gasless transaction,
* allowing a relayer to broadcast the transaction and potentially collect a fee for doing so.
*
* @param owner The user that signed the off-chain message and originator of the transfer.
* @param recipient The address that will receive the transferred DMM tokens.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param amount The amount of DMM that should be transferred from `owner` and sent to `recipient`.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee.
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
* @return True if the transfer was successful or false if it failed.
*/
function transferFromGaslessRequest(
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/interfaces/IUnderlyingTokenValuator.sol
pragma solidity ^0.5.0;
interface IUnderlyingTokenValuator {
/**
* @dev Gets the tokens value in terms of USD.
*
* @return The value of the `amount` of `token`, as a number with 18 decimals
*/
function getTokenValue(address token, uint amount) external view returns (uint);
}
// File: contracts/interfaces/IDmmTokenFactory.sol
pragma solidity ^0.5.0;
interface IDmmTokenFactory {
function deployToken(
string calldata symbol,
string calldata name,
uint8 decimals,
uint minMintAmount,
uint minRedeemAmount,
uint totalSupply,
address controller
) external returns (IDmmToken);
}
// File: contracts/interfaces/IPausable.sol
pragma solidity ^0.5.0;
interface IPausable {
function paused() external view returns (bool);
}
// File: contracts/interfaces/IOffChainCurrencyValuator.sol
pragma solidity ^0.5.0;
/**
* Gets the value of any currencies that are residing off-chain, but are NOT yet allocated to a revenue-producing asset.
*/
interface IOffChainCurrencyValuator {
/**
* @return The value of the off-chain assets. The number returned uses 18 decimal places.
*/
function getOffChainCurrenciesValue() external view returns (uint);
}
// File: contracts/impl/DmmController.sol
pragma solidity ^0.5.0;
contract DmmController is IPausable, Pausable, CommonConstants, IDmmController, Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
using Address for address;
/********************************
* Events
*/
event InterestRateInterfaceChanged(address previousInterestRateInterface, address newInterestRateInterface);
event OffChainAssetValuatorChanged(address previousOffChainAssetValuator, address newOffChainAssetValuator);
event OffChainCurrencyValuatorChanged(address previousOffChainCurrencyValuator, address newOffChainCurrencyValuator);
event UnderlyingTokenValuatorChanged(address previousUnderlyingTokenValuator, address newUnderlyingTokenValuator);
event MarketAdded(uint indexed dmmTokenId, address indexed dmmToken, address indexed underlyingToken);
event DisableMarket(uint indexed dmmTokenId);
event EnableMarket(uint indexed dmmTokenId);
event MinCollateralizationChanged(uint previousMinCollateralization, uint newMinCollateralization);
event MinReserveRatioChanged(uint previousMinReserveRatio, uint newMinReserveRatio);
/********************************
* Controller Fields
*/
DmmBlacklistable public dmmBlacklistable;
InterestRateInterface public interestRateInterface;
IOffChainCurrencyValuator public offChainCurrencyValuator;
IOffChainAssetValuator public offChainAssetsValuator;
IUnderlyingTokenValuator public underlyingTokenValuator;
IDmmTokenFactory public dmmTokenFactory;
IDmmTokenFactory public dmmEtherFactory;
uint public minCollateralization;
uint public minReserveRatio;
address public wethToken;
/********************************
* DMM Account Management
*/
mapping(uint => address) public dmmTokenIdToDmmTokenAddressMap;
mapping(address => uint) public dmmTokenAddressToDmmTokenIdMap;
mapping(address => uint) public underlyingTokenAddressToDmmTokenIdMap;
mapping(uint => address) public dmmTokenIdToUnderlyingTokenAddressMap;
mapping(uint => bool) public dmmTokenIdToIsDisabledMap;
uint[] public dmmTokenIds;
/********************************
* Constants
*/
uint public constant COLLATERALIZATION_BASE_RATE = 1e18;
uint public constant INTEREST_RATE_BASE_RATE = 1e18;
uint public constant MIN_RESERVE_RATIO_BASE_RATE = 1e18;
constructor(
address _interestRateInterface,
address _offChainAssetsValuator,
address _offChainCurrencyValuator,
address _underlyingTokenValuator,
address _dmmEtherFactory,
address _dmmTokenFactory,
address _dmmBlacklistable,
uint _minCollateralization,
uint _minReserveRatio,
address _wethToken
) public {
interestRateInterface = InterestRateInterface(_interestRateInterface);
offChainAssetsValuator = IOffChainAssetValuator(_offChainAssetsValuator);
offChainCurrencyValuator = IOffChainCurrencyValuator(_offChainCurrencyValuator);
underlyingTokenValuator = IUnderlyingTokenValuator(_underlyingTokenValuator);
dmmTokenFactory = IDmmTokenFactory(_dmmTokenFactory);
dmmEtherFactory = IDmmTokenFactory(_dmmEtherFactory);
dmmBlacklistable = DmmBlacklistable(_dmmBlacklistable);
minCollateralization = _minCollateralization;
minReserveRatio = _minReserveRatio;
wethToken = _wethToken;
}
/*****************
* Modifiers
*/
modifier whenNotPaused() {
require(!paused(), "ECOSYSTEM_PAUSED");
_;
}
modifier whenPaused() {
require(paused(), "ECOSYSTEM_NOT_PAUSED");
_;
}
modifier checkTokenExists(uint dmmTokenId) {
require(dmmTokenIdToDmmTokenAddressMap[dmmTokenId] != address(0x0), "TOKEN_DOES_NOT_EXIST");
_;
}
/**********************
* Public Functions
*/
function transferOwnership(address newOwner) public onlyOwner {
address oldOwner = owner();
super.transferOwnership(newOwner);
_removePauser(oldOwner);
_addPauser(newOwner);
}
function blacklistable() public view returns (Blacklistable) {
return dmmBlacklistable;
}
function addMarket(
address underlyingToken,
string memory symbol,
string memory name,
uint8 decimals,
uint minMintAmount,
uint minRedeemAmount,
uint totalSupply
) public onlyOwner {
require(underlyingTokenAddressToDmmTokenIdMap[underlyingToken] == 0, "TOKEN_ALREADY_EXISTS");
IDmmToken dmmToken;
address controller = address(this);
if (underlyingToken == wethToken) {
dmmToken = dmmEtherFactory.deployToken(
symbol,
name,
decimals,
minMintAmount,
minRedeemAmount,
totalSupply,
controller
);
} else {
dmmToken = dmmTokenFactory.deployToken(
symbol,
name,
decimals,
minMintAmount,
minRedeemAmount,
totalSupply,
controller
);
}
_addMarket(address(dmmToken), underlyingToken);
}
function addMarketFromExistingDmmToken(
address dmmToken,
address underlyingToken
)
onlyOwner
public {
require(underlyingTokenAddressToDmmTokenIdMap[underlyingToken] == 0, "TOKEN_ALREADY_EXISTS");
require(dmmToken.isContract(), "DMM_TOKEN_IS_NOT_CONTRACT");
require(underlyingToken.isContract(), "UNDERLYING_TOKEN_IS_NOT_CONTRACT");
require(Ownable(dmmToken).owner() == address(this), "INVALID_DMM_TOKEN_OWNERSHIP");
_addMarket(dmmToken, underlyingToken);
}
function transferOwnershipToNewController(
address newController
)
onlyOwner
public {
require(newController.isContract(), "NEW_CONTROLLER_IS_NOT_CONTRACT");
// All of the following contracts are owned by the controller. All other ownable contracts are owned by the
// same owner as this controller.
for (uint i = 0; i < dmmTokenIds.length; i++) {
address dmmToken = dmmTokenIdToDmmTokenAddressMap[dmmTokenIds[i]];
Ownable(dmmToken).transferOwnership(newController);
}
Ownable(address(dmmEtherFactory)).transferOwnership(newController);
Ownable(address(dmmTokenFactory)).transferOwnership(newController);
}
function enableMarket(uint dmmTokenId) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
require(dmmTokenIdToIsDisabledMap[dmmTokenId], "MARKET_ALREADY_ENABLED");
dmmTokenIdToIsDisabledMap[dmmTokenId] = false;
emit EnableMarket(dmmTokenId);
}
function disableMarket(uint dmmTokenId) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
require(!dmmTokenIdToIsDisabledMap[dmmTokenId], "MARKET_ALREADY_DISABLED");
dmmTokenIdToIsDisabledMap[dmmTokenId] = true;
emit DisableMarket(dmmTokenId);
}
function setInterestRateInterface(address newInterestRateInterface) public whenNotPaused onlyOwner {
address oldInterestRateInterface = address(interestRateInterface);
interestRateInterface = InterestRateInterface(newInterestRateInterface);
emit InterestRateInterfaceChanged(oldInterestRateInterface, address(interestRateInterface));
}
function setOffChainAssetValuator(address newOffChainAssetValuator) public whenNotPaused onlyOwner {
address oldOffChainAssetValuator = address(offChainAssetsValuator);
offChainAssetsValuator = IOffChainAssetValuator(newOffChainAssetValuator);
emit OffChainAssetValuatorChanged(oldOffChainAssetValuator, address(offChainAssetsValuator));
}
function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) public whenNotPaused onlyOwner {
address oldOffChainCurrencyValuator = address(offChainCurrencyValuator);
offChainCurrencyValuator = IOffChainCurrencyValuator(newOffChainCurrencyValuator);
emit OffChainCurrencyValuatorChanged(oldOffChainCurrencyValuator, address(offChainCurrencyValuator));
}
function setUnderlyingTokenValuator(address newUnderlyingTokenValuator) public whenNotPaused onlyOwner {
address oldUnderlyingTokenValuator = address(underlyingTokenValuator);
underlyingTokenValuator = IUnderlyingTokenValuator(newUnderlyingTokenValuator);
emit UnderlyingTokenValuatorChanged(oldUnderlyingTokenValuator, address(underlyingTokenValuator));
}
function setMinCollateralization(uint newMinCollateralization) public whenNotPaused onlyOwner {
uint oldMinCollateralization = minCollateralization;
minCollateralization = newMinCollateralization;
emit MinCollateralizationChanged(oldMinCollateralization, minCollateralization);
}
function setMinReserveRatio(uint newMinReserveRatio) public whenNotPaused onlyOwner {
uint oldMinReserveRatio = minReserveRatio;
minReserveRatio = newMinReserveRatio;
emit MinReserveRatioChanged(oldMinReserveRatio, minReserveRatio);
}
function increaseTotalSupply(
uint dmmTokenId,
uint amount
) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenId]).increaseTotalSupply(amount);
require(getTotalCollateralization() >= minCollateralization, "INSUFFICIENT_COLLATERAL");
}
function decreaseTotalSupply(
uint dmmTokenId,
uint amount
) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenId]).decreaseTotalSupply(amount);
}
function adminWithdrawFunds(
uint dmmTokenId,
uint underlyingAmount
) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
// Attempt to pull from the DMM contract into this contract, then send from this contract to sender.
IDmmToken token = IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenId]);
token.withdrawUnderlying(underlyingAmount);
IERC20 underlyingToken = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]);
underlyingToken.safeTransfer(_msgSender(), underlyingAmount);
// This is the amount owed by the system in terms of underlying
uint totalOwedAmount = token.activeSupply().mul(token.getCurrentExchangeRate()).div(EXCHANGE_RATE_BASE_RATE);
uint underlyingBalance = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]).balanceOf(address(token));
if (totalOwedAmount > 0) {
// IE if we owe 100 and have an underlying balance of 10 --> reserve ratio is 0.1
uint actualReserveRatio = underlyingBalance.mul(MIN_RESERVE_RATIO_BASE_RATE).div(totalOwedAmount);
require(actualReserveRatio >= minReserveRatio, "INSUFFICIENT_LEFTOVER_RESERVES");
}
emit AdminWithdraw(_msgSender(), underlyingAmount);
}
function adminDepositFunds(
uint dmmTokenId,
uint underlyingAmount
) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
// Attempt to pull from the sender into this contract, then have the DMM token pull from here.
IERC20 underlyingToken = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]);
underlyingToken.safeTransferFrom(_msgSender(), address(this), underlyingAmount);
address dmmTokenAddress = dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
underlyingToken.approve(dmmTokenAddress, underlyingAmount);
IDmmToken(dmmTokenAddress).depositUnderlying(underlyingAmount);
emit AdminDeposit(_msgSender(), underlyingAmount);
}
function getTotalCollateralization() public view returns (uint) {
uint totalLiabilities = 0;
uint totalAssets = 0;
for (uint i = 0; i < dmmTokenIds.length; i++) {
IDmmToken token = IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenIds[i]]);
uint currentExchangeRate = token.getCurrentExchangeRate();
// The interest rate is annualized, so figuring out the exchange rate 1-year from now is as simple as
// applying the current interest rate to the current exchange rate.
uint futureExchangeRate = currentExchangeRate.mul(INTEREST_RATE_BASE_RATE.add(getInterestRateByDmmTokenAddress(address(token)))).div(INTEREST_RATE_BASE_RATE);
uint totalSupply = IERC20(address(token)).totalSupply();
uint underlyingLiabilitiesForTotalSupply = getDmmSupplyValue(token, totalSupply, futureExchangeRate);
totalLiabilities = totalLiabilities.add(underlyingLiabilitiesForTotalSupply);
uint underlyingAssetsForTotalSupply = getDmmSupplyValue(token, totalSupply, currentExchangeRate);
totalAssets = totalAssets.add(underlyingAssetsForTotalSupply);
}
return getCollateralization(totalLiabilities, totalAssets);
}
function getActiveCollateralization() public view returns (uint) {
uint totalLiabilities = 0;
uint totalAssetsInDmmContract = 0;
for (uint i = 0; i < dmmTokenIds.length; i++) {
IDmmToken token = IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenIds[i]]);
uint underlyingLiabilitiesValue = getDmmSupplyValue(token, token.activeSupply(), token.getCurrentExchangeRate());
totalLiabilities = totalLiabilities.add(underlyingLiabilitiesValue);
IERC20 underlyingToken = IERC20(getUnderlyingTokenForDmm(address(token)));
uint underlyingAssetsValue = getUnderlyingSupplyValue(underlyingToken, underlyingToken.balanceOf(address(token)), token.decimals());
totalAssetsInDmmContract = totalAssetsInDmmContract.add(underlyingAssetsValue);
}
return getCollateralization(totalLiabilities, totalAssetsInDmmContract);
}
function getInterestRateByUnderlyingTokenAddress(address underlyingToken) public view returns (uint) {
uint dmmTokenId = underlyingTokenAddressToDmmTokenIdMap[underlyingToken];
return getInterestRateByDmmTokenId(dmmTokenId);
}
function getInterestRateByDmmTokenId(uint dmmTokenId) checkTokenExists(dmmTokenId) public view returns (uint) {
address dmmToken = dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
uint totalSupply = IERC20(dmmToken).totalSupply();
uint activeSupply = IDmmToken(dmmToken).activeSupply();
return interestRateInterface.getInterestRate(dmmTokenId, totalSupply, activeSupply);
}
function getInterestRateByDmmTokenAddress(address dmmToken) public view returns (uint) {
uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
uint totalSupply = IERC20(dmmToken).totalSupply();
uint activeSupply = IDmmToken(dmmToken).activeSupply();
return interestRateInterface.getInterestRate(dmmTokenId, totalSupply, activeSupply);
}
function getExchangeRateByUnderlying(address underlyingToken) public view returns (uint) {
address dmmToken = getDmmTokenForUnderlying(underlyingToken);
return IDmmToken(dmmToken).getCurrentExchangeRate();
}
function getExchangeRate(address dmmToken) public view returns (uint) {
uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
return IDmmToken(dmmToken).getCurrentExchangeRate();
}
function getDmmTokenForUnderlying(address underlyingToken) public view returns (address) {
uint dmmTokenId = underlyingTokenAddressToDmmTokenIdMap[underlyingToken];
require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
return dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
}
function getUnderlyingTokenForDmm(address dmmToken) public view returns (address) {
uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
return dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId];
}
function isMarketEnabledByDmmTokenId(uint dmmTokenId) checkTokenExists(dmmTokenId) public view returns (bool) {
return !dmmTokenIdToIsDisabledMap[dmmTokenId];
}
function isMarketEnabledByDmmTokenAddress(address dmmToken) public view returns (bool) {
uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
return !dmmTokenIdToIsDisabledMap[dmmTokenId];
}
function getTokenIdFromDmmTokenAddress(address dmmToken) public view returns (uint) {
uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
return dmmTokenId;
}
function getDmmTokenIds() public view returns (uint[] memory) {
return dmmTokenIds;
}
/**********************
* Private Functions
*/
function _addMarket(address dmmToken, address underlyingToken) private {
// Start the IDs at 1. Zero is reserved for the empty case when it doesn't exist.
uint dmmTokenId = dmmTokenIds.length + 1;
// Update the maps
dmmTokenIdToDmmTokenAddressMap[dmmTokenId] = dmmToken;
dmmTokenAddressToDmmTokenIdMap[dmmToken] = dmmTokenId;
underlyingTokenAddressToDmmTokenIdMap[underlyingToken] = dmmTokenId;
dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId] = underlyingToken;
// Misc. Structures
dmmTokenIdToIsDisabledMap[dmmTokenId] = false;
dmmTokenIds.push(dmmTokenId);
emit MarketAdded(dmmTokenId, dmmToken, underlyingToken);
}
function getCollateralization(uint totalLiabilities, uint totalAssets) private view returns (uint) {
if (totalLiabilities == 0) {
return 0;
}
uint collateralValue = offChainAssetsValuator.getOffChainAssetsValue().add(totalAssets).add(offChainCurrencyValuator.getOffChainCurrenciesValue());
return collateralValue.mul(COLLATERALIZATION_BASE_RATE).div(totalLiabilities);
}
function getDmmSupplyValue(IDmmToken dmmToken, uint dmmSupply, uint currentExchangeRate) private view returns (uint) {
uint underlyingTokenAmount = dmmSupply.mul(currentExchangeRate).div(EXCHANGE_RATE_BASE_RATE);
// The amount returned must use 18 decimal places, regardless of the # of decimals this token has.
uint standardizedUnderlyingTokenAmount;
if (dmmToken.decimals() == 18) {
standardizedUnderlyingTokenAmount = underlyingTokenAmount;
} else if (dmmToken.decimals() < 18) {
standardizedUnderlyingTokenAmount = underlyingTokenAmount.mul((10 ** (18 - uint(dmmToken.decimals()))));
} else /* decimals > 18 */ {
standardizedUnderlyingTokenAmount = underlyingTokenAmount.div((10 ** (uint(dmmToken.decimals()) - 18)));
}
address underlyingToken = getUnderlyingTokenForDmm(address(dmmToken));
return underlyingTokenValuator.getTokenValue(underlyingToken, standardizedUnderlyingTokenAmount);
}
function getUnderlyingSupplyValue(IERC20 underlyingToken, uint underlyingSupply, uint8 decimals) private view returns (uint) {
// The amount returned must use 18 decimal places, regardless of the # of decimals this token has.
uint standardizedUnderlyingTokenAmount;
if (decimals == 18) {
standardizedUnderlyingTokenAmount = underlyingSupply;
} else if (decimals < 18) {
standardizedUnderlyingTokenAmount = underlyingSupply.mul((10 ** (18 - uint(decimals))));
} else /* decimals > 18 */ {
standardizedUnderlyingTokenAmount = underlyingSupply.div((10 ** (uint(decimals) - 18)));
}
return underlyingTokenValuator.getTokenValue(address(underlyingToken), standardizedUnderlyingTokenAmount);
}
}File 11 of 14: CompoundRegistry
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interface/ICompound.sol
pragma solidity ^0.5.0;
contract ICompound {
function markets(address cToken)
external
view
returns (bool isListed, uint256 collateralFactorMantissa);
}
contract ICompoundToken is IERC20 {
function underlying() external view returns (address);
function exchangeRateStored() external view returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
}
contract ICompoundEther is IERC20 {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
}
// File: contracts/interface/ICompoundRegistry.sol
pragma solidity ^0.5.0;
contract ICompoundRegistry {
function tokenByCToken(ICompoundToken cToken) external view returns(IERC20);
function cTokenByToken(IERC20 token) external view returns(ICompoundToken);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/UniversalERC20.sol
pragma solidity ^0.5.0;
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount == 0) {
token.safeApprove(to, 0);
return;
}
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
function notExist(IERC20 token) internal pure returns(bool) {
return (address(token) == address(-1));
}
}
// File: contracts/CompoundRegistry.sol
pragma solidity ^0.5.0;
contract CompoundRegistry is Ownable, ICompoundRegistry {
using UniversalERC20 for IERC20;
ICompoundToken internal constant cETH = ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
IERC20 internal constant ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
mapping(address => address) private _tokenByCToken;
mapping(address => address) private _cTokenByToken;
function tokenByCToken(ICompoundToken cToken) external view returns(IERC20) {
if (cToken == cETH) {
return ETH;
}
return IERC20(_tokenByCToken[address(cToken)]);
}
function cTokenByToken(IERC20 token) external view returns(ICompoundToken) {
if (token.isETH()) {
return cETH;
}
return ICompoundToken(_cTokenByToken[address(token)]);
}
function addCToken(ICompoundToken cToken) public onlyOwner {
IERC20 token = IERC20(cToken.underlying());
_tokenByCToken[address(cToken)] = address(token);
_cTokenByToken[address(token)] = address(cToken);
}
function addCTokens(ICompoundToken[] calldata cTokens) external onlyOwner {
for (uint i = 0; i < cTokens.length; i++) {
addCToken(cTokens[i]);
}
}
}File 12 of 14: AaveRegistry
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interface/IAaveToken.sol
pragma solidity ^0.5.0;
contract IAaveToken is IERC20 {
function underlyingAssetAddress() external view returns (IERC20);
function redeem(uint256 amount) external;
}
interface IAaveLendingPool {
function core() external view returns (address);
function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
}
// File: contracts/interface/IAaveRegistry.sol
pragma solidity ^0.5.0;
contract IAaveRegistry {
function tokenByAToken(IAaveToken aToken) external view returns(IERC20);
function aTokenByToken(IERC20 token) external view returns(IAaveToken);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/UniversalERC20.sol
pragma solidity ^0.5.0;
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount == 0) {
token.safeApprove(to, 0);
return;
}
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
function notExist(IERC20 token) internal pure returns(bool) {
return (address(token) == address(-1));
}
}
// File: contracts/AaveRegistry.sol
pragma solidity ^0.5.0;
contract AaveRegistry is Ownable, IAaveRegistry {
using UniversalERC20 for IERC20;
IAaveToken internal constant aETH = IAaveToken(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04);
IERC20 internal constant ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
mapping(address => address) private _tokenByAToken;
mapping(address => address) private _aTokenByToken;
function tokenByAToken(IAaveToken aToken) external view returns(IERC20) {
if (aToken == aETH) {
return ETH;
}
return IERC20(_tokenByAToken[address(aToken)]);
}
function aTokenByToken(IERC20 token) external view returns(IAaveToken) {
if (token.isETH()) {
return aETH;
}
return IAaveToken(_aTokenByToken[address(token)]);
}
function addAToken(IAaveToken aToken) public onlyOwner {
IERC20 token = IERC20(aToken.underlyingAssetAddress());
_tokenByAToken[address(aToken)] = address(token);
_aTokenByToken[address(token)] = address(aToken);
}
function addATokens(IAaveToken[] calldata cTokens) external onlyOwner {
for (uint i = 0; i < cTokens.length; i++) {
addAToken(cTokens[i]);
}
}
}File 13 of 14: UniswapV2Factory
pragma solidity =0.5.16;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
contract UniswapV2Factory is IUniswapV2Factory {
address public feeTo;
address public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}File 14 of 14: TokenSpender
/**
*Submitted for verification at Etherscan.io on 2019-09-28
*/
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
library ExternalCall {
// Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function externalCall(address destination, uint value, bytes memory data, uint dataOffset, uint dataLength, uint gasLimit) internal returns(bool result) {
// solium-disable-next-line security/no-inline-assembly
if (gasLimit == 0) {
gasLimit = gasleft() - 40000;
}
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
gasLimit,
destination,
value,
add(d, dataOffset),
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > 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
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract IZrxExchange {
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
}
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 hash of the order (see IZrxExchange.getOrderHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s).
}
function getOrderInfo(Order memory order)
public
view
returns (OrderInfo memory orderInfo);
function getOrdersInfo(Order[] memory orders)
public
view
returns (OrderInfo[] memory ordersInfo);
function fillOrder(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (FillResults memory fillResults);
function fillOrderNoThrow(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (FillResults memory fillResults);
}
contract IGST2 is IERC20 {
function freeUpTo(uint256 value) external returns (uint256 freed);
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
function balanceOf(address who) external view returns (uint256);
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
contract Shutdownable is Ownable {
bool public isShutdown;
event Shutdown();
modifier notShutdown {
require(!isShutdown, "Smart contract is shut down.");
_;
}
function shutdown() public onlyOwner {
isShutdown = true;
emit Shutdown();
}
}
contract IERC20NonView {
// Methods are not view to avoid throw on proxy tokens with delegatecall inside
function balanceOf(address user) public returns(uint256);
function allowance(address from, address to) public returns(uint256);
}
contract ZrxMarketOrder {
using SafeMath for uint256;
function marketSellOrdersProportion(
IERC20 tokenSell,
address tokenBuy,
address zrxExchange,
address zrxTokenProxy,
IZrxExchange.Order[] calldata orders,
bytes[] calldata signatures,
uint256 mul,
uint256 div
)
external
{
uint256 amount = tokenSell.balanceOf(msg.sender).mul(mul).div(div);
this.marketSellOrders(tokenBuy, zrxExchange, zrxTokenProxy, amount, orders, signatures);
}
function marketSellOrders(
address makerAsset,
address zrxExchange,
address zrxTokenProxy,
uint256 takerAssetFillAmount,
IZrxExchange.Order[] calldata orders,
bytes[] calldata signatures
)
external
returns (IZrxExchange.FillResults memory totalFillResults)
{
for (uint i = 0; i < orders.length; i++) {
// Stop execution if the entire amount of takerAsset has been sold
if (totalFillResults.takerAssetFilledAmount >= takerAssetFillAmount) {
break;
}
// Calculate the remaining amount of takerAsset to sell
uint256 remainingTakerAmount = takerAssetFillAmount.sub(totalFillResults.takerAssetFilledAmount);
IZrxExchange.OrderInfo memory orderInfo = IZrxExchange(zrxExchange).getOrderInfo(orders[i]);
uint256 orderRemainingTakerAmount = orders[i].takerAssetAmount.sub(orderInfo.orderTakerAssetFilledAmount);
// Check available balance and allowance and update orderRemainingTakerAmount
{
uint256 balance = IERC20NonView(makerAsset).balanceOf(orders[i].makerAddress);
uint256 allowance = IERC20NonView(makerAsset).allowance(orders[i].makerAddress, zrxTokenProxy);
uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
if (availableTakerAmount < orderRemainingTakerAmount) {
orderRemainingTakerAmount = availableTakerAmount;
}
}
uint256 takerAmount = (orderRemainingTakerAmount < remainingTakerAmount) ? orderRemainingTakerAmount : remainingTakerAmount;
IZrxExchange.FillResults memory fillResults = IZrxExchange(zrxExchange).fillOrderNoThrow(
orders[i],
takerAmount,
signatures[i]
);
_addFillResults(totalFillResults, fillResults);
}
return totalFillResults;
}
function _addFillResults(
IZrxExchange.FillResults memory totalFillResults,
IZrxExchange.FillResults memory singleFillResults
)
internal
pure
{
totalFillResults.makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount.add(singleFillResults.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = totalFillResults.takerAssetFilledAmount.add(singleFillResults.takerAssetFilledAmount);
totalFillResults.makerFeePaid = totalFillResults.makerFeePaid.add(singleFillResults.makerFeePaid);
totalFillResults.takerFeePaid = totalFillResults.takerFeePaid.add(singleFillResults.takerFeePaid);
}
function getOrdersInfoRespectingBalancesAndAllowances(
IERC20 token,
IZrxExchange zrx,
address zrxTokenProxy,
IZrxExchange.Order[] memory orders
)
public
view
returns (IZrxExchange.OrderInfo[] memory ordersInfo)
{
ordersInfo = zrx.getOrdersInfo(orders);
for (uint i = 0; i < ordersInfo.length; i++) {
uint256 balance = token.balanceOf(orders[i].makerAddress);
uint256 allowance = token.allowance(orders[i].makerAddress, zrxTokenProxy);
uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
for (uint j = 0; j < i; j++) {
if (orders[j].makerAddress == orders[i].makerAddress) {
uint256 orderTakerAssetRemainigAmount = orders[j].takerAssetAmount.sub(
ordersInfo[j].orderTakerAssetFilledAmount
);
if (availableTakerAmount > orderTakerAssetRemainigAmount) {
availableTakerAmount = availableTakerAmount.sub(orderTakerAssetRemainigAmount);
} else {
availableTakerAmount = 0;
break;
}
}
}
uint256 remainingTakerAmount = orders[i].takerAssetAmount.sub(
ordersInfo[i].orderTakerAssetFilledAmount
);
if (availableTakerAmount < remainingTakerAmount) {
ordersInfo[i].orderTakerAssetFilledAmount = orders[i].takerAssetAmount.sub(availableTakerAmount);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal {
universalTransfer(token, to, amount, false);
}
function universalTransfer(IERC20 token, address to, uint256 amount, bool mayFail) internal returns(bool) {
if (amount == 0) {
return true;
}
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
if (mayFail) {
return address(uint160(to)).send(amount);
} else {
address(uint160(to)).transfer(amount);
return true;
}
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (token != ZERO_ADDRESS && token != ETH_ADDRESS) {
token.safeApprove(to, amount);
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
require(from == msg.sender && msg.value >= amount, "msg.value is zero");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
}
contract TokenSpender {
using SafeERC20 for IERC20;
address public owner;
IGST2 public gasToken;
address public gasTokenOwner;
constructor(IGST2 _gasToken, address _gasTokenOwner) public {
owner = msg.sender;
gasToken = _gasToken;
gasTokenOwner = _gasTokenOwner;
}
function claimTokens(IERC20 token, address who, address dest, uint256 amount) external {
require(msg.sender == owner, "Access restricted");
token.safeTransferFrom(who, dest, amount);
}
function burnGasToken(uint gasSpent) external {
require(msg.sender == owner, "Access restricted");
uint256 tokens = (gasSpent + 14154) / 41130;
gasToken.freeUpTo(tokens);
}
function() external {
if (msg.sender == gasTokenOwner) {
gasToken.transfer(msg.sender, gasToken.balanceOf(address(this)));
}
}
}