file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./full_match/4/0x5Fa046d6f146d49DB2855C571F8D8610BDE96091/sources/contracts/ERC721A.sol
|
See {IERC721Enumerable-totalSupply}./ Counter underflow is impossible as _burnCounter cannot be incremented more than _currentIndex times
|
function totalSupply() public view override returns (uint256) {
unchecked {
return _currentIndex - _burnCounter;
}
}
| 12,346,920
|
/**
*Submitted for verification at Etherscan.io on 2019-12-12
*/
pragma solidity ^0.5.0;
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
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(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
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));
return role.bearer[account];
}
}
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
newOwner = address(0);
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyNewOwner() {
require(msg.sender != address(0));
require(msg.sender == newOwner);
_;
}
function isOwner(address account) public view returns (bool) {
if( account == owner ){
return true;
}
else {
return false;
}
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
newOwner = _newOwner;
}
function acceptOwnership() public onlyNewOwner returns(bool) {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract PauserRole is Ownable{
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender)|| isOwner(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function removePauser(address account) public onlyOwner {
_removePauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, 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);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
/*
* approve/increaseApprove/decreaseApprove can be set when Paused state
*/
/*
* function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
* return super.approve(spender, value);
* }
*
* function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
* return super.increaseAllowance(spender, addedValue);
* }
*
* function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
* return super.decreaseAllowance(spender, subtractedValue);
* }
*/
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract LOG is ERC20Detailed, ERC20Pausable {
struct LockInfo {
uint256 _releaseTime;
uint256 _amount;
}
address public implementation;
mapping (address => LockInfo[]) public timelockList;
mapping (address => bool) public frozenAccount;
event Freeze(address indexed holder);
event Unfreeze(address indexed holder);
event Lock(address indexed holder, uint256 value, uint256 releaseTime);
event Unlock(address indexed holder, uint256 value);
modifier notFrozen(address _holder) {
require(!frozenAccount[_holder]);
_;
}
constructor() ERC20Detailed("LOGOS", "LOG", 18) public {
_mint(msg.sender, 1000000000 * (10 ** 18));
}
function balanceOf(address owner) public view returns (uint256) {
uint256 totalBalance = super.balanceOf(owner);
if( timelockList[owner].length >0 ){
for(uint i=0; i<timelockList[owner].length;i++){
totalBalance = totalBalance.add(timelockList[owner][i]._amount);
}
}
return totalBalance;
}
function transfer(address to, uint256 value) public notFrozen(msg.sender) returns (bool) {
if (timelockList[msg.sender].length > 0 ) {
_autoUnlock(msg.sender);
}
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public notFrozen(from) returns (bool) {
if (timelockList[from].length > 0) {
_autoUnlock(from);
}
return super.transferFrom(from, to, value);
}
function freezeAccount(address holder) public onlyPauser returns (bool) {
require(!frozenAccount[holder]);
require(timelockList[holder].length == 0);
frozenAccount[holder] = true;
emit Freeze(holder);
return true;
}
function unfreezeAccount(address holder) public onlyPauser returns (bool) {
require(frozenAccount[holder]);
frozenAccount[holder] = false;
emit Unfreeze(holder);
return true;
}
function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlyPauser returns (bool) {
_transfer(msg.sender, holder, value);
_lock(holder,value,releaseTime);
return true;
}
function unlock(address holder, uint256 idx) public onlyPauser returns (bool) {
require( timelockList[holder].length > idx, "There is not lock info.");
_unlock(holder,idx);
return true;
}
function _lock(address holder, uint256 value, uint256 releaseTime) internal returns(bool) {
_balances[holder] = _balances[holder].sub(value);
timelockList[holder].push( LockInfo(releaseTime, value) );
emit Lock(holder, value, releaseTime);
return true;
}
function _unlock(address holder, uint256 idx) internal returns(bool) {
LockInfo storage lockinfo = timelockList[holder][idx];
uint256 releaseAmount = lockinfo._amount;
delete timelockList[holder][idx];
timelockList[holder][idx] = timelockList[holder][timelockList[holder].length.sub(1)];
timelockList[holder].length -=1;
emit Unlock(holder, releaseAmount);
_balances[holder] = _balances[holder].add(releaseAmount);
return true;
}
function _autoUnlock(address holder) internal returns(bool) {
for(uint256 idx =0; idx < timelockList[holder].length ; idx++ ) {
if (timelockList[holder][idx]._releaseTime <= now) {
// If lockupinfo was deleted, loop restart at same position.
if( _unlock(holder, idx) ) {
idx -=1;
}
}
}
return true;
}
}
|
If lockupinfo was deleted, loop restart at same position.
|
function _autoUnlock(address holder) internal returns(bool) {
for(uint256 idx =0; idx < timelockList[holder].length ; idx++ ) {
if (timelockList[holder][idx]._releaseTime <= now) {
if( _unlock(holder, idx) ) {
idx -=1;
}
}
}
return true;
}
| 1,366,603
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
//
library SafeMath {
function ADD864(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB868(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB868(a, b, "SafeMath: subtraction overflow");
}
function SUB868(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL988(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function DIV926(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV926(a, b, "SafeMath: division by zero");
}
function DIV926(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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;
}
function MOD713(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD713(a, b, "SafeMath: modulo by zero");
}
function MOD713(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
//
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function SAFEAPPROVE567(address token, address to, uint value) internal { //inject NONSTANDARD NAMING
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function SAFETRANSFER962(address token, address to, uint value) internal { //inject NONSTANDARD NAMING
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function SAFETRANSFERFROM567(address token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function SAFETRANSFERETH46(address to, uint value) internal { //inject NONSTANDARD NAMING
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
//
library Math {
function MAX98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE252(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
//
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_entered371 = 1; //inject NONSTANDARD NAMING
uint256 private constant _entered907 = 2; //inject NONSTANDARD NAMING
uint256 private _status;
constructor () internal {
_status = _not_entered371;
}
modifier NONREENTRANT361() { //inject NONSTANDARD NAMING
// On the first call to nonReentrant, _notEntered will be true
require(_status != _entered907, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _entered907;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _not_entered371;
}
}
//
interface ICoFiXStakingRewards {
// Views
function REWARDSVAULT139() external view returns (address); //inject NONSTANDARD NAMING
function LASTBLOCKREWARDAPPLICABLE573() external view returns (uint256); //inject NONSTANDARD NAMING
function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING
function REWARDRATE36() external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING
function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING
// Mutative
function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING
function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING
function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING
function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING
function GETREWARD438() external; //inject NONSTANDARD NAMING
function GETREWARDANDSTAKE43() external; //inject NONSTANDARD NAMING
function EXIT912() external; //inject NONSTANDARD NAMING
function ADDREWARD881(uint256 amount) external; //inject NONSTANDARD NAMING
// Events
event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING
event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
}
//
interface ICoFiXVaultForLP {
enum POOL_STATE {INVALID, ENABLED, DISABLED}
event NEWPOOLADDED559(address pool, uint256 index); //inject NONSTANDARD NAMING
event POOLENABLED434(address pool); //inject NONSTANDARD NAMING
event POOLDISABLED539(address pool); //inject NONSTANDARD NAMING
function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING
function SETINITCOFIRATE698(uint256 _new) external; //inject NONSTANDARD NAMING
function SETDECAYPERIOD166(uint256 _new) external; //inject NONSTANDARD NAMING
function SETDECAYRATE667(uint256 _new) external; //inject NONSTANDARD NAMING
function ADDPOOL220(address pool) external; //inject NONSTANDARD NAMING
function ENABLEPOOL504(address pool) external; //inject NONSTANDARD NAMING
function DISABLEPOOL836(address pool) external; //inject NONSTANDARD NAMING
function SETPOOLWEIGHT937(address pool, uint256 weight) external; //inject NONSTANDARD NAMING
function BATCHSETPOOLWEIGHT100(address[] memory pools, uint256[] memory weights) external; //inject NONSTANDARD NAMING
function DISTRIBUTEREWARD70(address to, uint256 amount) external; //inject NONSTANDARD NAMING
function GETPENDINGREWARDOFLP590(address pair) external view returns (uint256); //inject NONSTANDARD NAMING
function CURRENTPERIOD82() external view returns (uint256); //inject NONSTANDARD NAMING
function CURRENTCOFIRATE163() external view returns (uint256); //inject NONSTANDARD NAMING
function CURRENTPOOLRATE277(address pool) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING
function CURRENTPOOLRATEBYPAIR255(address pair) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING
function STAKINGPOOLFORPAIR714(address pair) external view returns (address pool); //inject NONSTANDARD NAMING
function GETPOOLINFO427(address pool) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING
function GETPOOLINFOBYPAIR166(address pair) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING
function GETENABLEDPOOLCNT412() external view returns (uint256); //inject NONSTANDARD NAMING
function GETCOFISTAKINGPOOL12() external view returns (address pool); //inject NONSTANDARD NAMING
}
//
interface IERC20 {
function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER204(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE758(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE960(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM982(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER211(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL330(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
//
interface ICoFiStakingRewards {
// Views
function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING
function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING
// Mutative
function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING
function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING
function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING
function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING
function GETREWARD438() external; //inject NONSTANDARD NAMING
function ADDETHREWARD660() external payable; //inject NONSTANDARD NAMING
function EXIT912() external; //inject NONSTANDARD NAMING
// Events
event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event SAVINGWITHDRAWN125(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
}
//
interface ICoFiXFactory {
// All pairs: {ETH <-> ERC20 Token}
event PAIRCREATED889(address indexed token, address pair, uint256); //inject NONSTANDARD NAMING
event NEWGOVERNANCE470(address _new); //inject NONSTANDARD NAMING
event NEWCONTROLLER331(address _new); //inject NONSTANDARD NAMING
event NEWFEERECEIVER222(address _new); //inject NONSTANDARD NAMING
event NEWFEEVAULTFORLP508(address token, address feeVault); //inject NONSTANDARD NAMING
event NEWVAULTFORLP769(address _new); //inject NONSTANDARD NAMING
event NEWVAULTFORTRADER72(address _new); //inject NONSTANDARD NAMING
event NEWVAULTFORCNODE372(address _new); //inject NONSTANDARD NAMING
function CREATEPAIR976( //inject NONSTANDARD NAMING
address token
)
external
returns (address pair);
function GETPAIR599(address token) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS153(uint256) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH789() external view returns (uint256); //inject NONSTANDARD NAMING
function GETTRADEMININGSTATUS473(address token) external view returns (bool status); //inject NONSTANDARD NAMING
function SETTRADEMININGSTATUS493(address token, bool status) external; //inject NONSTANDARD NAMING
function GETFEEVAULTFORLP473(address token) external view returns (address feeVault); // for LPs //inject NONSTANDARD NAMING
function SETFEEVAULTFORLP669(address token, address feeVault) external; //inject NONSTANDARD NAMING
function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING
function SETCONTROLLER726(address _new) external; //inject NONSTANDARD NAMING
function SETFEERECEIVER908(address _new) external; //inject NONSTANDARD NAMING
function SETVAULTFORLP99(address _new) external; //inject NONSTANDARD NAMING
function SETVAULTFORTRADER40(address _new) external; //inject NONSTANDARD NAMING
function SETVAULTFORCNODE20(address _new) external; //inject NONSTANDARD NAMING
function GETCONTROLLER295() external view returns (address controller); //inject NONSTANDARD NAMING
function GETFEERECEIVER766() external view returns (address feeReceiver); // For CoFi Holders //inject NONSTANDARD NAMING
function GETVAULTFORLP604() external view returns (address vaultForLP); //inject NONSTANDARD NAMING
function GETVAULTFORTRADER901() external view returns (address vaultForTrader); //inject NONSTANDARD NAMING
function GETVAULTFORCNODE682() external view returns (address vaultForCNode); //inject NONSTANDARD NAMING
}
//
// Stake XToken to earn CoFi Token
contract CoFiXStakingRewards is ICoFiXStakingRewards, ReentrancyGuard {
using SafeMath for uint256;
address public override immutable rewardsToken; // CoFi
address public override immutable stakingToken; // XToken or CNode
address public immutable factory;
uint256 public lastUpdateBlock;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(
address _rewardsToken,
address _stakingToken,
address _factory
) public {
rewardsToken = _rewardsToken;
stakingToken = _stakingToken;
require(ICoFiXFactory(_factory).GETVAULTFORLP604() != address(0), "VaultForLP not set yet"); // check
factory = _factory;
lastUpdateBlock = 11040688; // https://etherscan.io/block/countdown/11040688
}
// replace cofixVault with rewardsVault, this could introduce more calls, but clear is more important
function REWARDSVAULT139() public virtual override view returns (address) { //inject NONSTANDARD NAMING
return ICoFiXFactory(factory).GETVAULTFORLP604();
}
function TOTALSUPPLY567() external override view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF980(address account) external override view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function LASTBLOCKREWARDAPPLICABLE573() public override view returns (uint256) { //inject NONSTANDARD NAMING
return block.number;
}
function REWARDPERTOKEN122() public override view returns (uint256) { //inject NONSTANDARD NAMING
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.ADD864(
ACCRUED168().MUL988(1e18).DIV926(_totalSupply)
);
}
function _REWARDPERTOKENANDACCRUED426() internal view returns (uint256, uint256) { //inject NONSTANDARD NAMING
if (_totalSupply == 0) {
// use the old rewardPerTokenStored, and accrued should be zero here
// if not the new accrued amount will never be distributed to anyone
return (rewardPerTokenStored, 0);
}
uint256 _accrued = ACCRUED168();
uint256 _rewardPerToken = rewardPerTokenStored.ADD864(
_accrued.MUL988(1e18).DIV926(_totalSupply)
);
return (_rewardPerToken, _accrued);
}
function REWARDRATE36() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING
return ICoFiXVaultForLP(REWARDSVAULT139()).CURRENTPOOLRATE277(address(this));
}
function ACCRUED168() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING
// calc block rewards
uint256 blockReward = LASTBLOCKREWARDAPPLICABLE573().SUB868(lastUpdateBlock).MUL988(REWARDRATE36());
// query pair trading rewards
uint256 tradingReward = ICoFiXVaultForLP(REWARDSVAULT139()).GETPENDINGREWARDOFLP590(stakingToken);
return blockReward.ADD864(tradingReward);
}
function EARNED893(address account) public override view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account].MUL988(REWARDPERTOKEN122().SUB868(userRewardPerTokenPaid[account])).DIV926(1e18).ADD864(rewards[account]);
}
function STAKE225(uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING
require(amount > 0, "Cannot stake 0");
_totalSupply = _totalSupply.ADD864(amount);
_balances[msg.sender] = _balances[msg.sender].ADD864(amount);
TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount);
emit STAKED268(msg.sender, amount);
}
function STAKEFOROTHER357(address other, uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(other) { //inject NONSTANDARD NAMING
require(amount > 0, "Cannot stake 0");
_totalSupply = _totalSupply.ADD864(amount);
_balances[other] = _balances[other].ADD864(amount);
TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount);
emit STAKEDFOROTHER964(msg.sender, other, amount);
}
function WITHDRAW360(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.SUB868(amount);
_balances[msg.sender] = _balances[msg.sender].SUB868(amount);
TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount);
emit WITHDRAWN805(msg.sender, amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function EMERGENCYWITHDRAW536() external override NONREENTRANT361 { //inject NONSTANDARD NAMING
uint256 amount = _balances[msg.sender];
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.SUB868(amount);
_balances[msg.sender] = 0;
rewards[msg.sender] = 0;
TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount);
emit EMERGENCYWITHDRAW7(msg.sender, amount);
}
function GETREWARD438() public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
// TransferHelper.safeTransfer(rewardsToken, msg.sender, reward);
uint256 transferred = _SAFECOFITRANSFER191(msg.sender, reward);
emit REWARDPAID501(msg.sender, transferred);
}
}
// get CoFi rewards and staking into CoFiStakingRewards pool
function GETREWARDANDSTAKE43() external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
address cofiStakingPool = ICoFiXVaultForLP(REWARDSVAULT139()).GETCOFISTAKINGPOOL12(); // also work for VaultForCNode
require(cofiStakingPool != address(0), "cofiStakingPool not set");
// approve to staking pool
address _rewardsToken = rewardsToken;
IERC20(_rewardsToken).APPROVE960(cofiStakingPool, reward);
ICoFiStakingRewards(cofiStakingPool).STAKEFOROTHER357(msg.sender, reward);
IERC20(_rewardsToken).APPROVE960(cofiStakingPool, 0); // ensure
emit REWARDPAID501(msg.sender, reward);
}
}
function EXIT912() external override { //inject NONSTANDARD NAMING
WITHDRAW360(_balances[msg.sender]);
GETREWARD438();
}
// add reward from trading pool or anyone else
function ADDREWARD881(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(address(0)) { //inject NONSTANDARD NAMING
// transfer from caller (router contract)
TransferHelper.SAFETRANSFERFROM567(rewardsToken, msg.sender, address(this), amount);
// update rewardPerTokenStored
rewardPerTokenStored = rewardPerTokenStored.ADD864(amount.MUL988(1e18).DIV926(_totalSupply));
emit REWARDADDED378(msg.sender, amount);
}
// Safe CoFi transfer function, just in case if rounding error or ending of mining causes pool to not have enough CoFis.
function _SAFECOFITRANSFER191(address _to, uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING
uint256 cofiBal = IERC20(rewardsToken).BALANCEOF980(address(this));
if (_amount > cofiBal) {
_amount = cofiBal;
}
TransferHelper.SAFETRANSFER962(rewardsToken, _to, _amount); // allow zero amount
return _amount;
}
modifier UPDATEREWARD178(address account) virtual { //inject NONSTANDARD NAMING
// rewardPerTokenStored = rewardPerToken();
// uint256 newAccrued = accrued();
(uint256 newRewardPerToken, uint256 newAccrued) = _REWARDPERTOKENANDACCRUED426();
rewardPerTokenStored = newRewardPerToken;
if (newAccrued > 0) {
// distributeReward could fail if CoFiXVaultForLP is not minter of CoFi anymore
// Should set reward rate to zero first, and then do a settlement of pool reward by call getReward
ICoFiXVaultForLP(REWARDSVAULT139()).DISTRIBUTEREWARD70(address(this), newAccrued);
}
lastUpdateBlock = LASTBLOCKREWARDAPPLICABLE573();
if (account != address(0)) {
rewards[account] = EARNED893(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING
event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
}
|
inject NONSTANDARD NAMING
|
function GETPOOLINFO427(address pool) external view returns (POOL_STATE state, uint256 weight);
| 1,840,733
|
./full_match/40/0x523073f029C889242beBFbB7eE3BDaB52942a39A/sources/contracts/FeeCollector.sol
|
returns the last time the reward was modified or periodFinish if the reward has ended
|
function lastTimeRewardApplicable(address token) public view returns (uint)
{
return Math.min(block.timestamp, periodFinish[token]);
}
| 9,544,752
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
//
/**
* @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);
}
//
/**
* @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;
}
}
//
/**
* @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);
}
}
}
}
//
/**
* @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");
}
}
}
//
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
* Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
//
/**
* @notice An account contracted created for each user address.
* @dev Anyone can directy deposit assets to the Account contract.
* @dev Only operators can withdraw asstes or perform operation from the Account contract.
*/
contract Account is Initializable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Asset is withdrawn from the Account.
*/
event Withdrawn(address indexed tokenAddress, address indexed targetAddress, uint256 amount);
/**
* @dev Spender is allowed to spend an asset.
*/
event Approved(address indexed tokenAddress, address indexed targetAddress, uint256 amount);
/**
* @dev A transaction is invoked on the Account.
*/
event Invoked(address indexed targetAddress, uint256 value, bytes data);
address public owner;
mapping(address => bool) public admins;
mapping(address => bool) public operators;
/**
* @dev Initializes the owner, admin and operator roles.
* @param _owner Address of the contract owner
* @param _initialAdmins The list of addresses that are granted the admin role.
*/
function initialize(address _owner, address[] memory _initialAdmins) public initializer {
owner = _owner;
// Grant the admin role to the initial admins
for (uint256 i = 0; i < _initialAdmins.length; i++) {
admins[_initialAdmins[i]] = true;
}
}
/**
* @dev Throws if called by any account that does not have operator role.
*/
modifier onlyOperator() {
require(isOperator(msg.sender), "not operator");
_;
}
/**
* @dev Transfers the ownership of the account to another address.
* The new owner can be an zero address which means renouncing the ownership.
* @param _owner New owner address
*/
function transferOwnership(address _owner) public {
require(msg.sender == owner, "not owner");
owner = _owner;
}
/**
* @dev Grants admin role to a new address.
* @param _account New admin address.
*/
function grantAdmin(address _account) public {
require(msg.sender == owner, "not owner");
require(!admins[_account], "already admin");
admins[_account] = true;
}
/**
* @dev Revokes the admin role from an address. Only owner can revoke admin.
* @param _account The admin address to revoke.
*/
function revokeAdmin(address _account) public {
require(msg.sender == owner, "not owner");
require(admins[_account], "not admin");
admins[_account] = false;
}
/**
* @dev Grants operator role to a new address. Only owner or admin can grant operator roles.
* @param _account The new operator address.
*/
function grantOperator(address _account) public {
require(msg.sender == owner || admins[msg.sender], "not admin");
require(!operators[_account], "already operator");
operators[_account] = true;
}
/**
* @dev Revoke operator role from an address. Only owner or admin can revoke operator roles.
* @param _account The operator address to revoke.
*/
function revokeOperator(address _account) public {
require(msg.sender == owner || admins[msg.sender], "not admin");
require(operators[_account], "not operator");
operators[_account] = false;
}
/**
* @dev Allows Account contract to receive ETH.
*/
receive() payable external {}
/**
* @dev Checks whether a user is an operator of the contract.
* Since admin role can grant operator role and owner can grant admin role, we treat both
* admins and owner as operators!
* @param userAddress Address to check whether it's an operator.
*/
function isOperator(address userAddress) public view returns (bool) {
return userAddress == owner || admins[userAddress] || operators[userAddress];
}
/**
* @dev Withdraws ETH from the Account contract. Only operators can withdraw ETH.
* @param targetAddress Address to send the ETH to.
* @param amount Amount of ETH to withdraw.
*/
function withdraw(address payable targetAddress, uint256 amount) public onlyOperator {
targetAddress.transfer(amount);
// Use address(-1) to represent ETH.
emit Withdrawn(address(-1), targetAddress, amount);
}
/**
* @dev Withdraws ERC20 token from the Account contract. Only operators can withdraw ERC20 tokens.
* @param tokenAddress Address of the ERC20 to withdraw.
* @param targetAddress Address to send the ERC20 to.
* @param amount Amount of ERC20 token to withdraw.
*/
function withdrawToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator {
IERC20(tokenAddress).safeTransfer(targetAddress, amount);
emit Withdrawn(tokenAddress, targetAddress, amount);
}
/**
* @dev Withdraws ERC20 token from the Account contract. If the Account contract does not have sufficient balance,
* try to withdraw from the owner's address as well. This is useful if users wants to keep assets in their own wallet
* by setting adequate allowance to the Account contract.
* @param tokenAddress Address of the ERC20 to withdraw.
* @param targetAddress Address to send the ERC20 to.
* @param amount Amount of ERC20 token to withdraw.
*/
function withdrawTokenFallThrough(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator {
uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this));
// If we have enough token balance, send the token directly.
if (tokenBalance >= amount) {
IERC20(tokenAddress).safeTransfer(targetAddress, amount);
emit Withdrawn(tokenAddress, targetAddress, amount);
} else {
IERC20(tokenAddress).safeTransferFrom(owner, targetAddress, amount.sub(tokenBalance));
IERC20(tokenAddress).safeTransfer(targetAddress, tokenBalance);
emit Withdrawn(tokenAddress, targetAddress, amount);
}
}
/**
* @dev Allows the spender address to spend up to the amount of token.
* @param tokenAddress Address of the ERC20 that can spend.
* @param targetAddress Address which can spend the ERC20.
* @param amount Amount of ERC20 that can be spent by the target address.
*/
function approveToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator {
IERC20(tokenAddress).safeApprove(targetAddress, 0);
if (amount > 0) {
IERC20(tokenAddress).safeApprove(targetAddress, amount);
}
emit Approved(tokenAddress, targetAddress, amount);
}
/**
* @notice Performs a generic transaction on the Account contract.
* @param target The address for the target contract.
* @param value The value of the transaction.
* @param data The data of the transaction.
*/
function invoke(address target, uint256 value, bytes memory data) public onlyOperator returns (bytes memory result) {
bool success;
(success, result) = target.call{value: value}(data);
if (!success) {
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
emit Invoked(target, value, data);
}
}
//
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*
* Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/Proxy.sol
*/
abstract contract Proxy {
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive () payable external {
_fallback();
}
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
//
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*
* Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
"Implementation not set"
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
emit Upgraded(newImplementation);
}
}
//
/**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
* Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol
*/
contract AdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
_setAdmin(_admin);
}
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function changeImplementation(address newImplementation) external ifAdmin {
_setImplementation(newImplementation);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
}
//
/**
* @notice Factory of Account contracts.
*/
contract AccountFactory {
/**
* @dev A new Account contract is created.
*/
event AccountCreated(address indexed userAddress, address indexed accountAddress);
address public governance;
address public accountBase;
mapping(address => address) public accounts;
/**
* @dev Constructor for Account Factory.
* @param _accountBase Base account implementation.
*/
constructor(address _accountBase) public {
require(_accountBase != address(0x0), "account base not set");
governance = msg.sender;
accountBase = _accountBase;
}
/**
* @dev Updates the base account implementation. Base account must be set.
*/
function setAccountBase(address _accountBase) public {
require(msg.sender == governance, "not governance");
require(_accountBase != address(0x0), "account base not set");
accountBase = _accountBase;
}
/**
* @dev Updates the govenance address. Governance can be empty address which means
* renouncing the governance.
*/
function setGovernance(address _governance) public {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Creates a new Account contract for the caller.
* Users can create multiple accounts by invoking this method multiple times. However,
* only the latest one is actively tracked and used by the platform.
* @param _initialAdmins The list of addresses that are granted the admin role.
*/
function createAccount(address[] memory _initialAdmins) public returns (Account) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(accountBase, msg.sender);
Account account = Account(address(proxy));
account.initialize(msg.sender, _initialAdmins);
accounts[msg.sender] = address(account);
emit AccountCreated(msg.sender, address(account));
return account;
}
}
//
/**
* @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;
}
}
//
/**
* @notice Interface for ERC20 token which supports minting new tokens.
*/
interface IERC20Mintable is IERC20 {
function mint(address _user, uint256 _amount) external;
}
//
/**
* @notice Interface for ERC20 token which supports mint and burn.
*/
interface IERC20MintableBurnable is IERC20Mintable {
function burn(uint256 _amount) external;
function burnFrom(address _user, uint256 _amount) external;
}
//
/**
* @notice ACoconut swap.
*/
contract ACoconutSwap is Initializable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Token swapped between two underlying tokens.
*/
event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought);
/**
* @dev New pool token is minted.
*/
event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount);
/**
* @dev Pool token is redeemed.
*/
event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount);
/**
* @dev Fee is collected.
*/
event FeeCollected(address indexed feeRecipient, uint256 feeAmount);
uint256 public constant feeDenominator = 10 ** 10;
address[] public tokens;
uint256[] public precisions; // 10 ** (18 - token decimals)
uint256[] public balances; // Converted to 10 ** 18
uint256 public mintFee; // Mint fee * 10**10
uint256 public swapFee; // Swap fee * 10**10
uint256 public redeemFee; // Redeem fee * 10**10
address public feeRecipient;
address public poolToken;
uint256 public totalSupply; // The total amount of pool token minted by the swap.
// It might be different from the pool token supply as the pool token can have multiple minters.
address public governance;
mapping(address => bool) public admins;
bool public paused;
uint256 public initialA;
/**
* @dev Initialize the ACoconut Swap.
*/
function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees,
address _poolToken, uint256 _A) public initializer {
require(_tokens.length == _precisions.length, "input mismatch");
require(_fees.length == 3, "no fees");
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != address(0x0), "token not set");
require(_precisions[i] != 0, "precision not set");
balances.push(0);
}
require(_poolToken != address(0x0), "pool token not set");
governance = msg.sender;
feeRecipient = msg.sender;
tokens = _tokens;
precisions = _precisions;
mintFee = _fees[0];
swapFee = _fees[1];
redeemFee = _fees[2];
poolToken = _poolToken;
initialA = _A;
// The swap must start with paused state!
paused = true;
}
/**
* @dev Returns the current value of A. This method might be updated in the future.
*/
function getA() public view returns (uint256) {
return initialA;
}
/**
* @dev Computes D given token balances.
* @param _balances Normalized balance of each token.
* @param _A Amplification coefficient from getA()
*/
function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) {
uint256 sum = 0;
uint256 i = 0;
uint256 Ann = _A;
for (i = 0; i < _balances.length; i++) {
sum = sum.add(_balances[i]);
Ann = Ann.mul(_balances.length);
}
if (sum == 0) return 0;
uint256 prevD = 0;
uint256 D = sum;
for (i = 0; i < 255; i++) {
uint256 pD = D;
for (uint256 j = 0; j < _balances.length; j++) {
// pD = pD * D / (_x * balance.length)
pD = pD.mul(D).div(_balances[j].mul(_balances.length));
}
prevD = D;
// D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD)
D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD)));
if (D > prevD) {
if (D - prevD <= 1) break;
} else {
if (prevD - D <= 1) break;
}
}
return D;
}
/**
* @dev Computes token balance given D.
* @param _balances Converted balance of each token except token with index _j.
* @param _j Index of the token to calculate balance.
* @param _D The target D value.
* @param _A Amplification coeffient.
* @return Converted balance of the token with index _j.
*/
function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) {
uint256 c = _D;
uint256 S_ = 0;
uint256 Ann = _A;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
Ann = Ann.mul(_balances.length);
if (i == _j) continue;
S_ = S_.add(_balances[i]);
// c = c * D / (_x * N)
c = c.mul(_D).div(_balances[i].mul(_balances.length));
}
// c = c * D / (Ann * N)
c = c.mul(_D).div(Ann.mul(_balances.length));
// b = S_ + D / Ann
uint256 b = S_.add(_D.div(Ann));
uint256 prevY = 0;
uint256 y = _D;
// 255 since the result is 256 digits
for (i = 0; i < 255; i++) {
prevY = y;
// y = (y * y + c) / (2 * y + b - D)
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D));
if (y > prevY) {
if (y - prevY <= 1) break;
} else {
if (prevY - y <= 1) break;
}
}
return y;
}
/**
* @dev Compute the amount of pool token that can be minted.
* @param _amounts Unconverted token balances.
* @return The amount of pool token minted.
*/
function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amounts.length == _balances.length, "invalid amount");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
// balance = balance + amount * precision
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD);
uint256 feeAmount = 0;
if (mintFee > 0) {
feeAmount = mintAmount.mul(mintFee).div(feeDenominator);
mintAmount = mintAmount.sub(feeAmount);
}
return (mintAmount, feeAmount);
}
/**
* @dev Mints new pool token.
* @param _amounts Unconverted token balances used to mint pool token.
* @param _minMintAmount Minimum amount of pool token to mint.
*/
function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can mint.
require(!paused || admins[msg.sender], "paused");
require(_balances.length == _amounts.length, "invalid amounts");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) {
// Initial deposit requires all tokens provided!
require(oldD > 0, "zero amount");
continue;
}
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD);
uint256 fee = mintFee;
uint256 feeAmount;
if (fee > 0) {
feeAmount = mintAmount.mul(fee).div(feeDenominator);
mintAmount = mintAmount.sub(feeAmount);
}
require(mintAmount >= _minMintAmount, "fewer than expected");
// Transfer tokens into the swap
for (i = 0; i < _amounts.length; i++) {
if (_amounts[i] == 0) continue;
// Update the balance in storage
balances[i] = _balances[i];
IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
totalSupply = newD;
IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount);
IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount);
emit Minted(msg.sender, mintAmount, _amounts, feeAmount);
}
/**
* @dev Computes the output amount after the swap.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @return Unconverted amount of token _j to swap out.
*/
function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) {
uint256[] memory _balances = balances;
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
// balance[i] = balance[i] + dx * precisions[i]
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
// dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
if (swapFee > 0) {
dy = dy.sub(dy.mul(swapFee).div(feeDenominator));
}
return dy;
}
/**
* @dev Exchange between two underlying tokens.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @param _minDy Minimum token _j to swap out in converted balance.
*/
function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can swap.
require(!paused || admins[msg.sender], "paused");
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
// balance[i] = balance[i] + dx * precisions[i]
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
// dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
// Update token balance in storage
balances[_j] = y;
balances[_i] = _balances[_i];
uint256 fee = swapFee;
if (fee > 0) {
dy = dy.sub(dy.mul(fee).div(feeDenominator));
}
require(dy >= _minDy, "fewer than expected");
IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx);
// Important: When swap fee > 0, the swap fee is charged on the output token.
// Therefore, balances[j] < tokens[j].balanceOf(this)
// Since balances[j] is used to compute D, D is unchanged.
// collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this)
// into pool token as fees!
IERC20(tokens[_j]).safeTransfer(msg.sender, dy);
emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy);
}
/**
* @dev Computes the amounts of underlying tokens when redeeming pool token.
* @param _amount Amount of pool tokens to redeem.
* @return Amounts of underlying tokens redeemed.
*/
function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) {
uint256[] memory _balances = balances;
require(_amount > 0, "zero amount");
uint256 D = totalSupply;
uint256[] memory amounts = new uint256[](_balances.length);
uint256 feeAmount = 0;
if (redeemFee > 0) {
feeAmount = _amount.mul(redeemFee).div(feeDenominator);
// Redemption fee is charged with pool token before redemption.
_amount = _amount.sub(feeAmount);
}
for (uint256 i = 0; i < _balances.length; i++) {
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use
// D in case we have multiple minters on the pool token.
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
}
return (amounts, feeAmount);
}
/**
* @dev Redeems pool token to underlying tokens proportionally.
* @param _amount Amount of pool token to redeem.
* @param _minRedeemAmounts Minimum amount of underlying tokens to get.
*/
function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
require(_amount > 0, "zero amount");
require(_balances.length == _minRedeemAmounts.length, "invalid mins");
uint256 D = totalSupply;
uint256[] memory amounts = new uint256[](_balances.length);
uint256 fee = redeemFee;
uint256 feeAmount;
if (fee > 0) {
feeAmount = _amount.mul(fee).div(feeDenominator);
// Redemption fee is paid with pool token
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
_amount = _amount.sub(feeAmount);
}
for (uint256 i = 0; i < _balances.length; i++) {
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use
// D in case we have multiple minters on the pool token.
uint256 tokenAmount = _balances[i].mul(_amount).div(D);
// Important: Underlying tokens must convert back to original decimals!
amounts[i] = tokenAmount.div(precisions[i]);
require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected");
// Updates the balance in storage
balances[i] = _balances[i].sub(tokenAmount);
IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]);
}
totalSupply = D.sub(_amount);
// After reducing the redeem fee, the remaining pool tokens are burned!
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
}
/**
* @dev Computes the amount when redeeming pool token to one specific underlying token.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the underlying token to redeem to.
* @return Amount of underlying token that can be redeem to.
*/
function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amount > 0, "zero amount");
require(_i < _balances.length, "invalid token");
uint256 A = getA();
uint256 D = totalSupply;
uint256 feeAmount = 0;
if (redeemFee > 0) {
feeAmount = _amount.mul(redeemFee).div(feeDenominator);
// Redemption fee is charged with pool token before redemption.
_amount = _amount.sub(feeAmount);
}
// The pool token amount becomes D - _amount
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
// dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors
uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]);
return (dy, feeAmount);
}
/**
* @dev Redeem pool token to one specific underlying token.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the token to redeem to.
* @param _minRedeemAmount Minimum amount of the underlying token to redeem to.
*/
function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
require(_amount > 0, "zero amount");
require(_i < _balances.length, "invalid token");
uint256 A = getA();
uint256 D = totalSupply;
uint256 fee = redeemFee;
uint256 feeAmount = 0;
if (fee > 0) {
// Redemption fee is charged with pool token before redemption.
feeAmount = _amount.mul(fee).div(feeDenominator);
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
_amount = _amount.sub(feeAmount);
}
// y is converted(18 decimals)
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
// dy is not converted
// dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors
uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]);
require(dy >= _minRedeemAmount, "fewer than expected");
// Updates token balance in storage
balances[_i] = y;
uint256[] memory amounts = new uint256[](_balances.length);
amounts[_i] = dy;
IERC20(tokens[_i]).safeTransfer(msg.sender, dy);
totalSupply = D.sub(_amount);
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
}
/**
* @dev Compute the amount of pool token that needs to be redeemed.
* @param _amounts Unconverted token balances.
* @return The amount of pool token that needs to be redeemed.
*/
function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amounts.length == balances.length, "length not match");
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
// balance = balance + amount * precision
_balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be smaller than or equal to oldD
uint256 redeemAmount = oldD.sub(newD);
uint256 feeAmount = 0;
if (redeemFee > 0) {
redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee));
feeAmount = redeemAmount.sub(oldD.sub(newD));
}
return (redeemAmount, feeAmount);
}
/**
* @dev Redeems underlying tokens.
* @param _amounts Amounts of underlying tokens to redeem to.
* @param _maxRedeemAmount Maximum of pool token to redeem.
*/
function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant {
uint256[] memory _balances = balances;
require(_amounts.length == balances.length, "length not match");
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
// balance = balance + amount * precision
_balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be smaller than or equal to oldD
uint256 redeemAmount = oldD.sub(newD);
uint256 fee = redeemFee;
uint256 feeAmount = 0;
if (fee > 0) {
redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee));
feeAmount = redeemAmount.sub(oldD.sub(newD));
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
}
require(redeemAmount <= _maxRedeemAmount, "more than expected");
// Updates token balances in storage.
balances = _balances;
uint256 burnAmount = redeemAmount.sub(feeAmount);
totalSupply = oldD.sub(burnAmount);
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, burnAmount);
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]);
}
emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount);
}
/**
* @dev Return the amount of fee that's not collected.
*/
function getPendingFeeAmount() external view returns (uint256) {
uint256[] memory _balances = balances;
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
_balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]);
}
uint256 newD = _getD(_balances, A);
return newD.sub(oldD);
}
/**
* @dev Collect fee based on the token balance difference.
*/
function collectFee() external returns (uint256) {
require(admins[msg.sender], "not admin");
uint256[] memory _balances = balances;
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
_balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]);
}
uint256 newD = _getD(_balances, A);
uint256 feeAmount = newD.sub(oldD);
if (feeAmount == 0) return 0;
balances = _balances;
totalSupply = newD;
address _feeRecipient = feeRecipient;
IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount);
emit FeeCollected(_feeRecipient, feeAmount);
return feeAmount;
}
/**
* @dev Updates the govenance address.
*/
function setGovernance(address _governance) external {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Updates the mint fee.
*/
function setMintFee(uint256 _mintFee) external {
require(msg.sender == governance, "not governance");
mintFee = _mintFee;
}
/**
* @dev Updates the swap fee.
*/
function setSwapFee(uint256 _swapFee) external {
require(msg.sender == governance, "not governance");
swapFee = _swapFee;
}
/**
* @dev Updates the redeem fee.
*/
function setRedeemFee(uint256 _redeemFee) external {
require(msg.sender == governance, "not governance");
redeemFee = _redeemFee;
}
/**
* @dev Updates the recipient of mint/swap/redeem fees.
*/
function setFeeRecipient(address _feeRecipient) external {
require(msg.sender == governance, "not governance");
require(_feeRecipient != address(0x0), "fee recipient not set");
feeRecipient = _feeRecipient;
}
/**
* @dev Updates the pool token.
*/
function setPoolToken(address _poolToken) external {
require(msg.sender == governance, "not governance");
require(_poolToken != address(0x0), "pool token not set");
poolToken = _poolToken;
}
/**
* @dev Pause mint/swap/redeem actions. Can unpause later.
*/
function pause() external {
require(msg.sender == governance, "not governance");
require(!paused, "paused");
paused = true;
}
/**
* @dev Unpause mint/swap/redeem actions.
*/
function unpause() external {
require(msg.sender == governance, "not governance");
require(paused, "not paused");
paused = false;
}
/**
* @dev Updates the admin role for the address.
* @param _account Address to update admin role.
* @param _allowed Whether the address is granted the admin role.
*/
function setAdmin(address _account, bool _allowed) external {
require(msg.sender == governance, "not governance");
require(_account != address(0x0), "account not set");
admins[_account] = _allowed;
}
}
//
/**
* @dev Application to help interact with ACoconutSwap with account.
*/
contract SwapApplication is Initializable {
using SafeMath for uint256;
address public governance;
ACoconutSwap public swap;
/**
* @dev Initializes swap application.
*/
function initialize(address _swap) external initializer {
require(_swap != address(0x0), "swap not set");
governance = msg.sender;
swap = ACoconutSwap(_swap);
}
/**
* @dev Updates the govenance address.
*/
function setGovernance(address _governance) external {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Updates the swap address.
*/
function setSwap(address _swap) external {
require(msg.sender == governance, "not governance");
require(_swap != address(0x0), "swap not set");
swap = ACoconutSwap(_swap);
}
modifier validAccount(address _account) {
Account account = Account(payable(_account));
require(account.owner() == msg.sender, "not owner");
require(account.isOperator(address(this)), "not operator");
_;
}
/**
* @dev Mints new pool token.
* @param _account The account address used to mint.
* @param _amounts Unconverted token balances used to mint pool token.
* @param _minMintAmount Minimum amount of pool token to mint.
*/
function mintToken(address _account, uint256[] calldata _amounts, uint256 _minMintAmount) external validAccount(_account) {
Account account = Account(payable(_account));
ACoconutSwap _swap = swap;
// We don't perform input validations here as they are done in ACoconutSwap.
for (uint256 i = 0; i < _amounts.length; i++) {
if (_amounts[i] == 0) continue;
account.approveToken(_swap.tokens(i), address(_swap), _amounts[i]);
}
bytes memory methodData = abi.encodeWithSignature("mint(uint256[],uint256)", _amounts, _minMintAmount);
account.invoke(address(_swap), 0, methodData);
}
/**
* @dev Exchange between two underlying tokens.
* @param _account The account address used to swap.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @param _minDy Minimum token _j to swap out in converted balance.
*/
function swapToken(address _account, uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external validAccount(_account) {
Account account = Account(payable(_account));
ACoconutSwap _swap = swap;
// We don't perform input validations here as they are done in ACoconutSwap.
account.approveToken(_swap.tokens(_i), address(_swap), _dx);
bytes memory methodData = abi.encodeWithSignature("swap(uint256,uint256,uint256,uint256)", _i, _j, _dx, _minDy);
account.invoke(address(_swap), 0, methodData);
}
/**
* @dev Redeems pool token to underlying tokens proportionally.
* @param _account The account address used to redeem.
* @param _amount Amount of pool token to redeem.
* @param _minRedeemAmounts Minimum amount of underlying tokens to get.
*/
function redeemProportion(address _account, uint256 _amount, uint256[] calldata _minRedeemAmounts) external validAccount(_account) {
Account account = Account(payable(_account));
ACoconutSwap _swap = swap;
// We don't perform input validations here as they are done in ACoconutSwap.
account.approveToken(_swap.poolToken(), address(_swap), _amount);
bytes memory methodData = abi.encodeWithSignature("redeemProportion(uint256,uint256[])", _amount, _minRedeemAmounts);
account.invoke(address(_swap), 0, methodData);
}
/**
* @dev Redeem pool token to one specific underlying token.
* @param _account The account address used to redeem.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the token to redeem to.
* @param _minRedeemAmount Minimum amount of the underlying token to redeem to.
*/
function redeemSingle(address _account, uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external validAccount(_account) {
Account account = Account(payable(_account));
ACoconutSwap _swap = swap;
// We don't perform input validations here as they are done in ACoconutSwap.
account.approveToken(_swap.poolToken(), address(_swap), _amount);
bytes memory methodData = abi.encodeWithSignature("redeemSingle(uint256,uint256,uint256)", _amount, _i, _minRedeemAmount);
account.invoke(address(_swap), 0, methodData);
}
/**
* @dev Redeems underlying tokens.
* @param _account The account address used to redeem.
* @param _amounts Amounts of underlying tokens to redeem to.
* @param _maxRedeemAmount Maximum of pool token to redeem.
*/
function redeemMulti(address _account, uint256[] calldata _amounts, uint256 _maxRedeemAmount) external validAccount(_account) {
Account account = Account(payable(_account));
ACoconutSwap _swap = swap;
// We don't perform input validations here as they are done in ACoconutSwap.
// The amount of acBTC to burn is unknown yet. Simply set the allowance to the maximum redeem amount.
account.approveToken(_swap.poolToken(), address(_swap), _maxRedeemAmount);
bytes memory methodData = abi.encodeWithSignature("redeemMulti(uint256[],uint256)", _amounts, _maxRedeemAmount);
account.invoke(address(_swap), 0, methodData);
// Clears the allowance afterward
account.approveToken(_swap.poolToken(), address(this), 0);
}
}
|
Mints new pool token. _account The account address used to mint. _amounts Unconverted token balances used to mint pool token. _minMintAmount Minimum amount of pool token to mint./ We don't perform input validations here as they are done in ACoconutSwap.
|
function mintToken(address _account, uint256[] calldata _amounts, uint256 _minMintAmount) external validAccount(_account) {
Account account = Account(payable(_account));
ACoconutSwap _swap = swap;
for (uint256 i = 0; i < _amounts.length; i++) {
if (_amounts[i] == 0) continue;
account.approveToken(_swap.tokens(i), address(_swap), _amounts[i]);
}
bytes memory methodData = abi.encodeWithSignature("mint(uint256[],uint256)", _amounts, _minMintAmount);
account.invoke(address(_swap), 0, methodData);
}
| 7,662,568
|
./full_match/1/0x70F2C0330528000BA806aE8F4254B45Ea980a34c/sources/contracts/core/RenovaCommandDeckBase.sol
|
Base class initializer function. _renovaAvatar The address of the Avatar contract. _renovaItem The address of the Item contract. _hashflowRouter The address of the Hashflow Router.
|
function __RenovaCommandDeckBase_init(
address _renovaAvatar,
address _renovaItem,
address _hashflowRouter,
address _questOwner
) internal onlyInitializing {
__Ownable_init();
require(
_renovaAvatar != address(0),
'RenovaCommandDeckBase::__RenovaCommandDeckBase_init RenovaAvatar not defined.'
);
require(
_renovaItem != address(0),
'RenovaCommandDeckBase::__RenovaCommandDeckBase_init RenovaItem not defined.'
);
require(
_hashflowRouter != address(0),
'RenovaCommandDeckBase::__RenovaCommandDeckBase_init HashflowRouter not defined.'
);
require(
_questOwner != address(0),
'RenovaCommandDeckBase::__RenovaCommandDeckBase_init Quest owner not defined.'
);
renovaAvatar = _renovaAvatar;
renovaItem = _renovaItem;
hashflowRouter = _hashflowRouter;
questOwner = _questOwner;
emit UpdateHashflowRouter(hashflowRouter, address(0));
emit UpdateQuestOwner(questOwner, address(0));
}
| 2,914,095
|
./full_match/1/0xaa282C8aB681fbD501A2B8fA0Ea558cbF5785F73/sources/contracts/AvocadoMultisig/AvocadoMultisigCore.sol
|
action ran out of gas. can not add action index as that again might run out of gas. keep revert minimal
|
function _handleActionFailure(uint256 actionMinGasLeft_, uint256 i, bytes memory result_) internal view {
if (gasleft() < actionMinGasLeft_) {
revert("AVO__OUT_OF_GAS");
}
revert(string.concat(Strings.toString(i), _getRevertReasonFromReturnedData(result_)));
}
| 3,129,018
|
pragma solidity ^0.4.23;
import "../libraries/StateMachine.sol";
import "../pandora/IPandora.sol";
import "../jobs/IComputingJob.sol";
import "./IWorkerNode.sol";
/**
* @title Worker Node Smart Contract
* @author "Dr Maxim Orlovsky" <orlovsky@pandora.foundation>
*
* @dev # Worker Node Smart Contract
*
* Worker node contract accumulates funds/payments for performed cognitive work and contains inalienable reputation.
* Note: In Pyrrha there is no mining. In the following versions all mined coins will be also assigned to the
* `WorkerNode` contract
*
* Worker node acts as a state machine and each its function can be evoked only in some certain states. That"s
* why each function must have state machine-controlled function modifiers. Contract state is managed by
* - Worker node code (second level of consensus)
* - Main Pandora contract [Pandora.sol]
* - Worker node contract itself
*/
contract WorkerNode is IWorkerNode, StateMachine /* final */ {
/**
* ## State Machine extensions
*/
/// @dev Modifier requiring contract to be preset in one of the active states (`Assigned`, `ReadyForDataValidation`,
/// `ValidatingData`, `ReadyForComputing`, `Computing`); otherwise an exception is generated and the function
/// does not execute
modifier requireActiveStates() {
require(
stateMachine.currentState == Assigned ||
stateMachine.currentState == ReadyForDataValidation ||
stateMachine.currentState == ValidatingData ||
stateMachine.currentState == ReadyForComputing ||
stateMachine.currentState == Computing);
_;
}
/// @dev Private method initializing state machine. Must be called only once from the contract constructor
function _initStateMachine() internal {
// Creating table of possible state transitions
mapping(uint8 => uint8[]) transitions = stateMachine.transitionTable;
transitions[Uninitialized] = [Idle, Offline, InsufficientStake];
transitions[Offline] = [Idle];
transitions[Idle] = [Offline, UnderPenalty, Assigned, Destroyed];
transitions[Assigned] = [Offline, UnderPenalty, ReadyForDataValidation];
transitions[ReadyForDataValidation] = [ValidatingData, Offline, UnderPenalty, Idle];
transitions[UnderPenalty] = [Offline, InsufficientStake, Idle];
transitions[ValidatingData] = [Offline, Idle, UnderPenalty, ReadyForComputing];
transitions[ReadyForComputing] = [Computing, Offline, UnderPenalty, Idle];
transitions[Computing] = [Offline, UnderPenalty, Idle];
transitions[InsufficientStake] = [Offline, Idle, Destroyed];
// Initializing state machine via base contract code
super._initStateMachine();
// Going into initial state (Offline)
stateMachine.currentState = Offline;
}
/**
* ## Main implementation
*/
/// ### Public variables
/// @notice Reference to the main Pandora contract.
/// @dev Required to check the validity of the method calls coming from the Pandora contract.
/// Initialy set from the address supplied to the constructor and can"t be changed after.
IPandora public pandora;
/// @notice Active cognitive job reference. Zero when there is no active cognitive job assigned or performed
/// @dev Valid (non-zero) only for active states (see `activeStates` modified for the list of such states)
IComputingJob public activeJob;
event WorkerDestroyed();
/// ### Constructor and destructor
constructor(
IPandora _pandora /// Reference to the main Pandora contract that creates Worker Node
)
public {
require(_pandora != address(0));
pandora = _pandora;
// There should be no active cognitive job upon contract creation
activeJob = IComputingJob(0);
// Initialize state machine (state transition table and initial state). Always must be performed at the very
// end of contract constructor code.
_initStateMachine();
}
/// ### Function modifiers
/// @dev Modifier for functions that can be called only by the main Pandora contract
modifier onlyPandora() {
require(pandora != address(0));
require(msg.sender == address(pandora));
_;
}
/// @dev Modifier for functions that can be called only by one of the active cognitive jobs performed under
/// main Pandora contract. It includes jobs _not_ assigned to the worker node
modifier onlyCognitiveJob() {
require(pandora != address(0));
IComputingJob sender = IComputingJob(msg.sender);
require(pandora == sender.pandora());
require(pandora.isActiveJob(sender));
_;
}
/// @dev Modifier for functions that can be called only by the cognitive job assigned or performed by the worker
/// node in one of its active states
modifier onlyActiveCognitiveJob() {
require(msg.sender == address(activeJob));
_;
}
function destroy()
external
onlyPandora {
/// Call event before doing the actual contract suicide
emit WorkerDestroyed();
/// Suiciding
selfdestruct(owner);
}
/// ### External and public functions
function alive(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(Offline)
transitionToState(Idle)
{
// Nothing to do here
}
/// @notice Do not call
/// @dev Assigns cognitive job to the worker. Can be called only by one of active cognitive jobs listed under
/// the main Pandora contract
function assignJob(
/// @dev Cognitive job to be assigned
IComputingJob _job
) external // Can"t be called internally
/// @dev Must be called only by one of active cognitive jobs listed under the main Pandora contract
onlyCognitiveJob
/// @dev Job can be assigned only to Idle workers
requireState(Idle)
/// @dev Successful completion must transition worker to an `Assigned` stage
transitionToState(Assigned)
{
activeJob = _job;
}
function cancelJob(
// No arguments
) external // Can"t be called internally
onlyActiveCognitiveJob
requireActiveStates
transitionToState(Idle)
{
activeJob = IComputingJob(0);
}
function acceptAssignment(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(Assigned)
transitionToState(ReadyForDataValidation)
{
require(activeJob != IComputingJob(0));
activeJob.gatheringWorkersResponse(true);
}
function declineAssignment(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(Assigned)
transitionToState(Idle)
{
require(activeJob != IComputingJob(0));
activeJob.gatheringWorkersResponse(false);
}
function processToDataValidation(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(ReadyForDataValidation)
transitionToState(ValidatingData)
{
// All actual work is done by function modifiers
}
function acceptValidData(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(ValidatingData)
transitionToState(ReadyForComputing)
{
require(activeJob != IComputingJob(0));
activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Accept);
}
function declineValidData(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(ValidatingData)
transitionToState(Idle)
{
require(activeJob != IComputingJob(0));
activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Decline);
}
function reportInvalidData(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(ValidatingData)
transitionToState(Idle)
{
require(activeJob != IComputingJob(0));
activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Invalid);
}
function processToCognition(
// No arguments
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(ReadyForComputing)
transitionToState(Computing)
{
// All actual work is done by function modifiers
}
function provideResults(
bytes _ipfsAddress
) external // Can"t be called internally
/* @fixme onlyOwner */
requireState(Computing)
transitionToState(Idle)
{
require(activeJob != IComputingJob(0));
activeJob.completeWork(_ipfsAddress);
}
/// @notice Withdraws full balance to the owner account. Can be called only by the owner of the contract.
function withdrawBalance(
// No arguments
) external // Can"t be called internally
onlyOwner // Can be called only by the owner
requireStates2(Idle, Offline)
{
/// @todo Handle stakes etc
owner.transfer(address(this).balance);
}
}
|
No arguments @fixme onlyOwner /
|
function declineAssignment(
requireState(Assigned)
transitionToState(Idle)
{
require(activeJob != IComputingJob(0));
activeJob.gatheringWorkersResponse(false);
}
| 14,102,302
|
./full_match/56/0xD803719B1a6Aac1dcB2c815d987f0CB5E8f4cCAf/sources/happy.sol
|
solhint-disable-next-line func-name-mixedcase
|
interface IERC20Permit {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns(uint256);
function DOMAIN_SEPARATOR() external view returns(bytes32);
}
| 3,238,523
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol';
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract CREWCoin is Initializable, UUPSUpgradeable, ERC721EnumerableUpgradeable, OwnableUpgradeable {
address payable public qtWallet;
address _signer;
uint256 public minted;
string public baseURI;
string _name;
string _symbol;
mapping(bytes32 => uint) public skuHash;
function initialize(string memory _uri, address payable _qtWallet, address __signer) initializer public {
__ERC721_init('CREW Coin', 'CREW');
__Ownable_init();
__UUPSUpgradeable_init();
qtWallet = _qtWallet;
_signer = __signer;
baseURI = _uri;
_symbol = 'CREW';
_name = 'CREW Coin';
minted = 13; // match with the current variable minted at address 0x46A9E5b490175724699D09F0F6104c95DEfd447a
// transferOwnership(0x86a8A293fB94048189F76552eba5EC47bc272223);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
receive() payable external {}
function setBaseURI(string memory _newURI) external onlyOwner {
baseURI = _newURI;
}
function setSigner(address __signer) external onlyOwner {
_signer = __signer;
}
function mint(bytes32 sku, uint timestamp, bytes memory signature, address to) external virtual {
require(recover(sku, timestamp, signature, to), "Signature Verifier: Invalid sigature");
require(skuHash[sku] == 0, "Doji already used");
require(_msgSender() == to, "Only rank 9 owner can mint the token");
require(timestamp >= block.timestamp, "SignatureVerifier: Signature expired");
skuHash[sku] = minted;
_safeMint(to, minted);
++minted;
}
function setMinted(uint _startTokenId) external onlyOwner virtual {
minted = _startTokenId;
}
function walletDistro() external {
AddressUpgradeable.sendValue(qtWallet, address(this).balance);
}
function changeWallets(address payable _qtWallet) external onlyOwner {
qtWallet = _qtWallet;
}
function walletInventory(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function burn(uint256 tokenId) external {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId));
_burn(tokenId);
}
//THIS IS MANDATORY or REMOVE DO NOT FORGET
function _baseURI() internal view virtual override returns (string memory){
return baseURI;
}
function _getMessageHash(bytes32 sku, uint timestamp, address to) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _getMessage(sku, timestamp, to)));
}
function _getMessage(bytes32 sku, uint timestamp, address to) internal view returns (bytes32) {
return keccak256(abi.encodePacked(sku, _msgSender(),timestamp, to));
}
function recover(bytes32 sku, uint timestamp, bytes memory signature, address to) public view returns(bool) {
bytes32 hash = _getMessageHash(sku, timestamp, to);
return SignatureChecker.isValidSignatureNow(_signer, hash, signature);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @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");
(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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @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.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual 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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @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");
(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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
|
transferOwnership(0x86a8A293fB94048189F76552eba5EC47bc272223);
|
function initialize(string memory _uri, address payable _qtWallet, address __signer) initializer public {
__ERC721_init('CREW Coin', 'CREW');
__Ownable_init();
__UUPSUpgradeable_init();
qtWallet = _qtWallet;
_signer = __signer;
baseURI = _uri;
_symbol = 'CREW';
_name = 'CREW Coin';
}
| 6,251,850
|
./partial_match/56/0xA80a8d99b1d96fdBdb9cbFA0a96a288D66265B4C/sources/ThePoolLP3.sol
|
stakeFor visibility is public as overriding LPTokenWrapper's stakeFor() function
|
function stakeFor(address staker,uint256 amount) public override updateReward(staker) {
require(msg.sender==devFund,"Unauthorized account.");
require(amount > 0, "Cannot stake 0");
super.stakeFor(staker,amount);
emit Staked(staker);
}
| 11,096,988
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
contract EncryptedSender {
struct TopicData {
// An (optional) public key used to encrypt messages for this topic. This is only necessary if the sender will
// not have access to the public key offchain.
bytes publicKey;
// The encrypted message.
bytes message;
}
struct Recipient {
// This maps from a hash to the data for this topic.
// Note: the hash is a hash of the "subject" or "topic" of the message.
mapping(bytes32 => TopicData) topics;
// This contains the set of all authorized senders for this recipient.
mapping(address => bool) authorizedSenders;
}
mapping(address => Recipient) private recipients;
/**
* @notice Authorizes `sender` to send messages to the caller.
*/
function addAuthorizedSender(address sender) external {
recipients[msg.sender].authorizedSenders[sender] = true;
}
/**
* @notice Revokes `sender`'s authorization to send messages to the caller.
*/
function removeAuthorizedSender(address sender) external {
recipients[msg.sender].authorizedSenders[sender] = false;
}
/**
* @notice Gets the current stored message corresponding to `recipient` and `topicHash`.
* @dev To decrypt messages (this requires access to the recipient's private keys), use the decryptMessage()
* function in common/Crypto.js.
*/
function getMessage(address recipient, bytes32 topicHash) external view returns (bytes memory) {
return recipients[recipient].topics[topicHash].message;
}
/**
* @notice Gets the stored public key for a particular `recipient` and `topicHash`. Return value will be 0 length
* if no public key has been set.
* @dev Senders may need this public key to encrypt messages that only the `recipient` can read. If the public key
* is communicated offchain, this field may be left empty.
*/
function getPublicKey(address recipient, bytes32 topicHash) external view returns (bytes memory) {
return recipients[recipient].topics[topicHash].publicKey;
}
/**
* @notice Sends `message` to `recipient_` categorized by a particular `topicHash`. This will overwrite any
* previous messages sent to this `recipient` with this `topicHash`.
* @dev To construct an encrypted message, use the encryptMessage() in common/Crypto.js.
* The public key for the recipient can be obtained using the getPublicKey() method.
*/
function sendMessage(address recipient_, bytes32 topicHash, bytes memory message) public {
Recipient storage recipient = recipients[recipient_];
require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to send to this recipient");
recipient.topics[topicHash].message = message;
}
function removeMessage(address recipient_, bytes32 topicHash) public {
Recipient storage recipient = recipients[recipient_];
require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to remove message");
delete recipient.topics[topicHash].message;
}
/**
* @notice Sets the public key for this caller and topicHash.
* @dev Note: setting the public key is optional - if the publicKey is communicated or can be derived offchain by
* the sender, there is no need to set it here. Because there are no specific requirements for the publicKey, there
* is also no verification of its validity other than its length.
*/
function setPublicKey(bytes memory publicKey, bytes32 topicHash) public {
require(publicKey.length == 64, "Public key is the wrong length");
recipients[msg.sender].topics[topicHash].publicKey = publicKey;
}
/**
* @notice Returns true if the `sender` is authorized to send to the `recipient`.
*/
function isAuthorizedSender(address sender, address recipient) public view returns (bool) {
// Note: the recipient is always authorized to send messages to themselves.
return recipients[recipient].authorizedSenders[sender] || recipient == sender;
}
}
library FixedPoint {
using SafeMath for uint;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint 10^77.
uint private constant FP_SCALING_FACTOR = 10**18;
struct Unsigned {
uint rawValue;
}
/** @dev Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. */
function fromUnscaledUint(uint a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/** @dev Whether `a` is greater than `b`. */
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/** @dev Whether `a` is greater than `b`. */
function isGreaterThan(Unsigned memory a, uint b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/** @dev Whether `a` is greater than `b`. */
function isGreaterThan(uint a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/** @dev Whether `a` is less than `b`. */
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/** @dev Whether `a` is less than `b`. */
function isLessThan(Unsigned memory a, uint b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/** @dev Whether `a` is less than `b`. */
function isLessThan(uint a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/** @dev Adds two `Unsigned`s, reverting on overflow. */
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/** @dev Adds an `Unsigned` to an unscaled uint, reverting on overflow. */
function add(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/** @dev Subtracts two `Unsigned`s, reverting on underflow. */
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/** @dev Subtracts an unscaled uint from an `Unsigned`, reverting on underflow. */
function sub(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/** @dev Subtracts an `Unsigned` from an unscaled uint, reverting on underflow. */
function sub(uint a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/** @dev Multiplies two `Unsigned`s, reverting on overflow. */
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/** @dev Multiplies an `Unsigned` by an unscaled uint, reverting on overflow. */
function mul(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/** @dev Divides with truncation two `Unsigned`s, reverting on overflow or division by 0. */
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/** @dev Divides with truncation an `Unsigned` by an unscaled uint, reverting on division by 0. */
function div(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/** @dev Divides with truncation an unscaled uint by an `Unsigned`, reverting on overflow or division by 0. */
function div(uint a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/** @dev Raises an `Unsigned` to the power of an unscaled uint, reverting on overflow. E.g., `b=2` squares `a`. */
function pow(Unsigned memory a, uint b) internal pure returns (Unsigned memory output) {
// TODO(ptare): Consider using the exponentiation by squaring technique instead:
// https://en.wikipedia.org/wiki/Exponentiation_by_squaring
output = fromUnscaledUint(1);
for (uint i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint => Role) private roles;
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
*/
function holdsRole(uint roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
require(false, "Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, exclusive role.
*/
function resetMember(uint roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
*/
function getMember(uint roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the
* managing role for `roleId`.
*/
function addMember(uint roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the
* managing role for `roleId`.
*/
function removeMember(uint roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(uint roleId, uint managingRoleId, address[] memory initialMembers)
internal
onlyInvalidRole(roleId)
{
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role");
}
/**
* @notice Internal method to initialize a exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(uint roleId, uint managingRoleId, address initialMember)
internal
onlyInvalidRole(roleId)
{
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role");
}
}
interface OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Returns the time at which the user should expect the price to be resolved. 0 means the price has already
* been resolved.
*/
function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime);
/**
* @notice Whether the Oracle provides prices for this identifier.
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
/**
* @notice Whether the price for `identifier` and `time` is available.
*/
function hasPrice(bytes32 identifier, uint time) external view returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
*/
function getPrice(bytes32 identifier, uint time) external view returns (int price);
}
interface RegistryInterface {
/**
* @dev Registers a new derivative. Only authorized derivative creators can call this method.
*/
function registerDerivative(address[] calldata counterparties, address derivativeAddress) external;
/**
* @dev Returns whether the derivative has been registered with the registry (and is therefore an authorized.
* participant in the UMA system).
*/
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered);
/**
* @dev Returns a list of all derivatives that are associated with a particular party.
*/
function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives);
/**
* @dev Returns all registered derivatives.
*/
function getAllRegisteredDerivatives() external view returns (address[] memory derivatives);
}
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint;
enum Roles {
// The owner manages the set of DerivativeCreators.
Owner,
// Can register derivatives.
DerivativeCreator
}
// Array of all derivatives that are approved to use the UMA Oracle.
address[] private registeredDerivatives;
// This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered.
enum PointerValidity {
Invalid,
Valid
}
struct Pointer {
PointerValidity valid;
uint128 index;
}
// Maps from derivative address to a pointer that refers to that registered derivative in `registeredDerivatives`.
mapping(address => Pointer) private derivativePointers;
// Note: this must be stored outside of `registeredDerivatives` because mappings cannot be deleted and copied
// like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose
// of the Pointer struct and break separation of concern between referential data and data.
struct PartiesMap {
mapping(address => bool) parties;
}
// Maps from derivative address to the set of parties that are involved in that derivative.
mapping(address => PartiesMap) private derivativesToParties;
event NewDerivativeRegistered(address indexed derivativeAddress, address indexed creator, address[] parties);
constructor() public {
_createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender);
// Start with no derivative creators registered.
_createSharedRole(uint(Roles.DerivativeCreator), uint(Roles.Owner), new address[](0));
}
function registerDerivative(address[] calldata parties, address derivativeAddress)
external
onlyRoleHolder(uint(Roles.DerivativeCreator))
{
// Create derivative pointer.
Pointer storage pointer = derivativePointers[derivativeAddress];
// Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double
// registered).
require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(derivativeAddress);
// No length check necessary because we should never hit (2^127 - 1) derivatives.
pointer.index = uint128(registeredDerivatives.length.sub(1));
// Set up PartiesMap for this derivative.
PartiesMap storage partiesMap = derivativesToParties[derivativeAddress];
for (uint i = 0; i < parties.length; i = i.add(1)) {
partiesMap.parties[parties[i]] = true;
}
address[] memory partiesForEvent = parties;
emit NewDerivativeRegistered(derivativeAddress, msg.sender, partiesForEvent);
}
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) {
return derivativePointers[derivative].valid == PointerValidity.Valid;
}
function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives) {
// This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long
// as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy
// the array over to the return array, which is allocated using the correct size. Note: this is done by double
// copying each value rather than storing some referential info (like indices) in memory to reduce the number
// of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1).
address[] memory tmpDerivativeArray = new address[](registeredDerivatives.length);
uint outputIndex = 0;
for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) {
address derivative = registeredDerivatives[i];
if (derivativesToParties[derivative].parties[party]) {
// Copy selected derivative to the temporary array.
tmpDerivativeArray[outputIndex] = derivative;
outputIndex = outputIndex.add(1);
}
}
// Copy the temp array to the return array that is set to the correct size.
derivatives = new address[](outputIndex);
for (uint j = 0; j < outputIndex; j = j.add(1)) {
derivatives[j] = tmpDerivativeArray[j];
}
}
function getAllRegisteredDerivatives() external view returns (address[] memory derivatives) {
return registeredDerivatives;
}
}
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int currentMode;
}
/**
* @dev Returns whether the result is resolved, and if so, what value it resolved to. `price` should be ignored if
* `isResolved` is false.
* @param minVoteThreshold Minimum number of tokens that must have been voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int price)
{
// TODO(ptare): Figure out where this parameter is supposed to come from.
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)) {
// `modeThreshold` and `minVoteThreshold` are met, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @dev Adds a new vote to be used when computing the result.
*/
function addVote(Data storage data, int votePrice, FixedPoint.Unsigned memory numberTokens)
internal
{
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (votePrice != data.currentMode
&& data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])) {
data.currentMode = votePrice;
}
}
/**
* @dev Checks whether a `voteHash` is considered correct. Should only be called after a vote is resolved, i.e.,
* via `getResolvedPrice`.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @dev Gets the total number of tokens whose votes are considered correct. Should only be called after a vote is
* resolved, i.e., via `getResolvedPrice`.
*/
function getTotalCorrectlyVotedTokens(Data storage data)
internal
view
returns (FixedPoint.Unsigned memory)
{
return data.voteFrequency[data.currentMode];
}
}
contract Testable {
// Is the contract being run on the test network. Note: this variable should be set on construction and never
// modified.
bool public isTest;
uint private currentTime;
constructor(bool _isTest) internal {
isTest = _isTest;
if (_isTest) {
currentTime = now; // solhint-disable-line not-rely-on-time
}
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(isTest);
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
*/
function setCurrentTime(uint _time) external onlyIfTest {
currentTime = _time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
*/
function getCurrentTime() public view returns (uint) {
if (isTest) {
return currentTime;
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
contract Governor is MultiRole, Testable {
using SafeMath for uint;
enum Roles {
// Can set the proposer.
Owner,
// Address that can make proposals.
Proposer
}
struct Transaction {
address to;
uint value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint requestTime;
}
Finder private finder;
Proposal[] public proposals;
/**
* @notice Emitted when a new proposal is created.
*/
event NewProposal(uint indexed id, Transaction[] transactions);
/**
* @notice Emitted when an existing proposal is executed.
*/
event ProposalExecuted(uint indexed id, uint transactionIndex);
constructor(address _finderAddress, bool _isTest) public Testable(_isTest) {
finder = Finder(_finderAddress);
_createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender);
_createExclusiveRole(uint(Roles.Proposer), uint(Roles.Owner), msg.sender);
}
/**
* @notice Executes a proposed governance action that has been approved by voters. This can be called by anyone.
*/
function executeProposal(uint id, uint transactionIndex) external {
Proposal storage proposal = proposals[id];
int price = _getVoting().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction storage transaction = proposal.transactions[transactionIndex];
require(transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous transaction has not been executed");
require(transaction.to != address(0), "Transaction has already been executed");
require(price != 0, "Cannot execute, proposal was voted down");
require(_executeCall(transaction.to, transaction.value, transaction.data), "Transaction execution failed");
// Delete the transaction.
delete proposal.transactions[transactionIndex];
emit ProposalExecuted(id, transactionIndex);
}
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
*/
function numProposals() external view returns (uint) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* Note: after a proposal is executed, its data will be zeroed out.
*/
function getProposal(uint id) external view returns (Proposal memory proposal) {
return proposals[id];
}
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions the list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that disallows structs arrays to be passed to
* external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint(Roles.Proposer)) {
uint id = proposals.length;
uint time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add an element to the proposals array.
proposals.length = proposals.length.add(1);
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
proposal.transactions.length = transactions.length;
for (uint i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The to address cannot be 0x0");
proposal.transactions[i] = transactions[i];
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
Voting voting = _getVoting();
voting.addSupportedIdentifier(identifier);
// Note: this check is only here to appease slither.
require(voting.requestPrice(identifier, time) != ~uint(0), "Proposal will never be considered");
voting.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
function _constructIdentifier(uint id) private pure returns (bytes32 identifier) {
bytes32 bytesId = _uintToBytes(id);
return _addPrefix(bytesId, "Admin ", 6);
}
function _executeCall(address to, uint256 value, bytes memory data)
private
returns (bool success)
{
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas, to, value, inputData, inputDataSize, 0, 0)
}
}
function _getVoting() private view returns (Voting voting) {
return Voting(finder.getImplementationAddress("Oracle"));
}
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToBytes(uint v) private pure returns (bytes32 ret) {
if (v == 0) {
ret = "0";
} else {
while (v > 0) {
ret = ret >> 8;
ret |= bytes32((v % 10) + 48) << (31 * 8);
v /= 10;
}
}
return ret;
}
function _addPrefix(bytes32 input, bytes32 prefix, uint prefixLength) private pure returns (bytes32 output) {
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
library VoteTiming {
using SafeMath for uint;
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
enum Phase {
Commit,
Reveal
}
// Note: this MUST match the number of values in the enum above.
uint private constant NUM_PHASES = 2;
struct Data {
uint roundId;
uint roundStartTime;
uint phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input and resets the round id and round
* start time to 1 and 0 respectively.
* @dev This method should generally only be run once, but it can also be used to reset the data structure to its
* initial values.
*/
function init(Data storage data, uint phaseLength) internal {
data.phaseLength = phaseLength;
data.roundId = 1;
data.roundStartTime = 0;
}
/**
* @notice Gets the most recently stored round ID set by updateRoundId().
*/
function getLastUpdatedRoundId(Data storage data) internal view returns (uint) {
return data.roundId;
}
/**
* @notice Determines whether time has advanced far enough to advance to the next voting round and update the
* stored round id.
*/
function shouldUpdateRoundId(Data storage data, uint currentTime) internal view returns (bool) {
(uint roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime);
return data.roundId != roundId;
}
/**
* @notice Updates the round id. Note: if shouldUpdateRoundId() returns false, this method will have no effect.
*/
function updateRoundId(Data storage data, uint currentTime) internal {
(data.roundId, data.roundStartTime) = _getCurrentRoundIdAndStartTime(data, currentTime);
}
/**
* @notice Computes what the stored round id would be if it were updated right now, but this method does not
* commit the update.
*/
function computeCurrentRoundId(Data storage data, uint currentTime) internal view returns (uint roundId) {
(roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime);
}
/**
* @notice Computes the current phase based only on the current time.
*/
function computeCurrentPhase(Data storage data, uint currentTime) internal view returns (Phase) {
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return Phase(currentTime.div(data.phaseLength).mod(NUM_PHASES));
}
/**
* @notice Gets the end time of the current round or any round in the future. Note: this method will revert if
* the roundId < getLastUpdatedRoundId().
*/
function computeEstimatedRoundEndTime(Data storage data, uint roundId) internal view returns (uint) {
// The add(1) is because we want the round end time rather than the start time, so it's really the start of
// the next round.
uint roundDiff = roundId.sub(data.roundId).add(1);
uint roundLength = data.phaseLength.mul(NUM_PHASES);
return data.roundStartTime.add(roundDiff.mul(roundLength));
}
/**
* @dev Computes an updated round id and round start time based on the current time.
*/
function _getCurrentRoundIdAndStartTime(Data storage data, uint currentTime)
private
view
returns (uint roundId, uint startTime)
{
uint currentStartTime = data.roundStartTime;
// Return current data if time has moved backwards.
if (currentTime <= data.roundStartTime) {
return (data.roundId, data.roundStartTime);
}
// Get the start of the round that currentTime would be a part of by flooring by roundLength.
uint roundLength = data.phaseLength.mul(NUM_PHASES);
startTime = currentTime.div(roundLength).mul(roundLength);
// Only increment the round ID if the start time has changed.
if (startTime > currentStartTime) {
roundId = data.roundId.add(1);
} else {
roundId = data.roundId;
}
}
}
contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint time;
}
/**
* @notice Commit your vote for a price request for `identifier` at `time`.
* @dev (`identifier`, `time`) must correspond to a price request that's currently in the commit phase. `hash`
* should be the keccak256 hash of the price you want to vote for and a `int salt`. Commits can be changed.
*/
function commitVote(bytes32 identifier, uint time, bytes32 hash) external;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price` and `salt` must match the latest `hash` that `commitVote()` was called with. Only the
* committer can reveal their vote.
*/
function revealVote(bytes32 identifier, uint time, int price, int salt) external;
/**
* @notice Gets the queries that are being voted on this round.
*/
function getPendingRequests() external view returns (PendingRequest[] memory);
/**
* @notice Gets the current vote phase (commit or reveal) based on the current block time.
*/
function getVotePhase() external view returns (VoteTiming.Phase);
/**
* @notice Gets the current vote round id based on the current block time.
*/
function getCurrentRoundId() external view returns (uint);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
*/
function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory) public returns
(FixedPoint.Unsigned memory);
}
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;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
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);
}
}
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;
}
}
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;
}
}
contract Finder is Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @dev Updates the address of the contract that implements `interfaceName`.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @dev Gets the address of the contract that implements the given `interfaceName`.
*/
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address implementationAddress)
{
implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "No implementation for interface found");
}
}
contract Voting is Testable, Ownable, OracleInterface, VotingInterface, EncryptedSender {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint time;
// A map containing all votes for this price in various rounds.
mapping(uint => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint index;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint time;
int price;
int salt;
}
struct Round {
// Voting token snapshot ID for this round. If this is 0, no snapshot has been taken.
uint snapshotId;
// Inflation rate set for this round.
FixedPoint.Unsigned inflationRate;
}
// Represents the status a price request has.
enum RequestStatus {
// Was never requested.
NotRequested,
// Is being voted on in the current round.
Active,
// Was resolved in a previous round.
Resolved,
// Is scheduled to be voted on in a future round.
Future
}
// Maps round numbers to the rounds.
mapping(uint => Round) private rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved. These requests may be for future
// rounds.
bytes32[] private pendingPriceRequests;
VoteTiming.Data private voteTiming;
// The set of identifiers the oracle can provide verified prices for.
mapping(bytes32 => bool) private supportedIdentifiers;
// Percentage of the total token supply that must be used in a vote to create a valid price resolution.
// 1 == 100%.
FixedPoint.Unsigned private gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters. Note: this value is used to set per-round inflation at the beginning
// of each round.
// 1 = 100%
FixedPoint.Unsigned private inflationRate;
// Reference to the voting token.
VotingToken private votingToken;
// Reference to the Finder.
Finder private finder;
// If non-zero, this contract has been migrated to this address. All voters and financial contracts should query the
// new address only.
address private migratedAddress;
// Max value of an unsigned integer.
uint constant private UINT_MAX = ~uint(0);
event VoteCommitted(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time);
event VoteRevealed(
address indexed voter,
uint indexed roundId,
bytes32 indexed identifier,
uint time,
int price,
uint numTokens
);
event RewardsRetrieved(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time,
uint numTokens);
event PriceRequestAdded(uint indexed votingRoundId, bytes32 indexed identifier, uint time);
event PriceResolved(uint indexed resolutionRoundId, bytes32 indexed identifier, uint time, int price);
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/**
* @notice Construct the Voting contract.
* @param phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage percentage of the total token supply that must be used in a vote to create a valid price
* resolution.
* @param _isTest whether this contract is being constructed for the purpose of running automated tests.
*/
constructor(
uint phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
address _votingToken,
address _finder,
bool _isTest
) public Testable(_isTest) {
voteTiming.init(phaseLength);
// TODO(#779): GAT percentage must be < 100%
require(_gatPercentage.isLessThan(1));
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = Finder(_finder);
}
modifier onlyRegisteredDerivative() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress);
} else {
Registry registry = Registry(finder.getImplementationAddress("Registry"));
// TODO(#779): Must be registered derivative
require(registry.isDerivativeRegistered(msg.sender));
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0));
_;
}
function requestPrice(bytes32 identifier, uint time)
external
onlyRegisteredDerivative()
returns (uint expectedTime)
{
uint blockTime = getCurrentTime();
// TODO(#779): Price request must be for a time in the past
require(time <= blockTime);
// TODO(#779): Price request for unsupported identifier
require(supportedIdentifiers[identifier]);
// Must ensure the round is updated here so the requested price will be voted on in the next commit cycle.
_updateRound(blockTime);
bytes32 priceRequestId = _encodePriceRequest(identifier, time);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return voteTiming.computeEstimatedRoundEndTime(currentRoundId);
} else if (requestStatus == RequestStatus.Resolved) {
return 0;
} else if (requestStatus == RequestStatus.Future) {
return voteTiming.computeEstimatedRoundEndTime(priceRequest.lastVotingRound);
}
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
// Estimate the end of next round and return the time.
return voteTiming.computeEstimatedRoundEndTime(nextRoundId);
}
function batchCommit(Commitment[] calldata commits) external {
for (uint i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].hash);
} else {
commitAndPersistEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].hash,
commits[i].encryptedVote);
}
}
}
function batchReveal(Reveal[] calldata reveals) external {
for (uint i = 0; i < reveals.length; i++) {
revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt);
}
}
/**
* @notice Disables this Voting contract in favor of the migrated one.
*/
function setMigrated(address newVotingAddress) external onlyOwner {
migratedAddress = newVotingAddress;
}
/**
* @notice Adds the provided identifier as a supported identifier. Price requests using this identifier will be
* succeed after this call.
*/
function addSupportedIdentifier(bytes32 identifier) external onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist. Price requests using this identifier will no longer succeed
* after this call.
*/
function removeSupportedIdentifier(bytes32 identifier) external onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
function isIdentifierSupported(bytes32 identifier) external view returns (bool) {
return supportedIdentifiers[identifier];
}
function hasPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (bool _hasPrice) {
(_hasPrice, ,) = _getPriceOrError(identifier, time);
}
function getPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (int) {
(bool _hasPrice, int price, string memory message) = _getPriceOrError(identifier, time);
// TODO(#779): If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
function getPendingRequests() external view returns (PendingRequest[] memory pendingRequests) {
uint blockTime = getCurrentTime();
uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that `isActive()`.
PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length);
uint numUnresolved = 0;
for (uint i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequest(
{ identifier: priceRequest.identifier, time: priceRequest.time });
numUnresolved++;
}
}
pendingRequests = new PendingRequest[](numUnresolved);
for (uint i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
}
function getVotePhase() external view returns (VoteTiming.Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
function getCurrentRoundId() external view returns (uint) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
function commitVote(bytes32 identifier, uint time, bytes32 hash) public onlyIfNotMigrated() {
// TODO(#779): Committed hash of 0 is disallowed, choose a different salt
require(hash != bytes32(0));
// Current time is required for all vote timing queries.
uint blockTime = getCurrentTime();
// TODO(#779): Cannot commit while in the reveal phase
require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Commit);
// Should only update the round in the commit phase because a new round that's already in the reveal phase
// would be wasted.
_updateRound(blockTime);
// At this point, the computed and last updated round ID should be equal.
uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
// TODO(#779): Cannot commit on inactive request
require(_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time);
}
function revealVote(bytes32 identifier, uint time, int price, int salt) public onlyIfNotMigrated() {
uint blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Reveal,
"Cannot reveal while in the commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the
// round is over.
uint roundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
require(voteSubmission.commit != bytes32(0), "Cannot reveal an uncommitted or previously revealed hash");
require(keccak256(abi.encode(price, salt)) == voteSubmission.commit,
"Committed hash doesn't match revealed price and salt");
delete voteSubmission.commit;
// Get or create a snapshot for this round.
uint snapshotId = _getOrCreateSnapshotId(roundId);
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
// Remove the stored message for this price request, if it exists.
bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId));
removeMessage(msg.sender, topicHash);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue);
}
function commitAndPersistEncryptedVote(
bytes32 identifier,
uint time,
bytes32 hash,
bytes memory encryptedVote
) public {
commitVote(identifier, time, hash);
uint roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId));
sendMessage(msg.sender, topicHash, encryptedVote);
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
*/
function setInflationRate(FixedPoint.Unsigned memory _inflationRate) public onlyOwner {
inflationRate = _inflationRate;
}
function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory toRetrieve)
public
returns (FixedPoint.Unsigned memory totalRewardToIssue)
{
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress);
}
uint blockTime = getCurrentTime();
_updateRound(blockTime);
require(roundId < voteTiming.computeCurrentRoundId(blockTime));
Round storage round = rounds[roundId];
FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(
votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(
votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
require(priceRequest.lastVotingRound == roundId, "Only retrieve rewards for votes resolved in same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)) {
// The price was successfully resolved during the voter's last voting round, the voter revealed and was
// correct, so they are elgible for a reward.
FixedPoint.Unsigned memory correctTokens = voteInstance.resultComputation.
getTotalCorrectlyVotedTokens();
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(correctTokens);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time,
reward.rawValue);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue));
}
}
/*
* @dev Checks to see if there is a price that has or can be resolved for an (identifier, time) pair.
* @returns a boolean noting whether a price is resolved, the price, and an error string if necessary.
*/
function _getPriceOrError(bytes32 identifier, uint time)
private
view
returns (bool _hasPrice, int price, string memory err)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
uint currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "The current voting round has not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price will be voted on in the future");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(bytes32 identifier, uint time) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time)];
}
function _encodePriceRequest(bytes32 identifier, uint time) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time));
}
function _getOrCreateSnapshotId(uint roundId) private returns (uint) {
Round storage round = rounds[roundId];
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
}
return round.snapshotId;
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve an unresolved price request");
// Delete the resolved price request from pendingPriceRequests.
uint lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
delete pendingPriceRequests[lastIndex];
priceRequest.index = UINT_MAX;
emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice);
}
function _updateRound(uint blockTime) private {
if (!voteTiming.shouldUpdateRoundId(blockTime)) {
return;
}
uint nextVotingRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Set the round inflation rate to the current global inflation rate.
rounds[nextVotingRoundId].inflationRate = inflationRate;
// Update the stored round to the current one.
voteTiming.updateRoundId(blockTime);
}
function _computeGat(uint roundId) private view returns (FixedPoint.Unsigned memory) {
uint snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snaphotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
}
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);
}
contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint value) external;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint value) external returns (bool);
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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 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 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 {
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);
}
/** @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 {
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);
}
/**
* @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 {
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);
}
/**
* @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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Snapshot is ERC20 {
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
event Snapshot(uint256 id);
// Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a
// balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid
// when required, but is also flexible enough that it allows for e.g. daily snapshots.
function snapshot() public returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
contract VotingToken is ExpandedIERC20, ERC20Snapshot, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
// Standard ERC20 metadata.
string public constant name = "UMA Voting Token v1"; // solhint-disable-line const-name-snakecase
string public constant symbol = "UMA"; // solhint-disable-line const-name-snakecase
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
constructor() public {
_createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender);
_createSharedRole(uint(Roles.Minter), uint(Roles.Owner), new address[](0));
_createSharedRole(uint(Roles.Burner), uint(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
*/
function mint(address recipient, uint value) external onlyRoleHolder(uint(Roles.Minter)) returns (bool) {
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
*/
function burn(uint value) external onlyRoleHolder(uint(Roles.Burner)) {
_burn(msg.sender, value);
}
}
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
|
Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. `initialMembers` will be immediately added to the role. Should be called by derived contracts, usually at construction time. Will revert if the role is already initialized./
|
function _createSharedRole(uint roleId, uint managingRoleId, address[] memory initialMembers)
internal
onlyInvalidRole(roleId)
{
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role");
}
| 1,827,066
|
./partial_match/1/0x43434343d4869d9B340e1B00feC1e6924aD08E43/sources/StringToken.sol
|
Returns if the seed is free/
|
function isSeedFree(uint256 seed) public view returns (bool) {
return (_seedUsed[seed] == false);
}
| 15,603,290
|
pragma solidity ^0.4.21;
// SecureWallet - A smart contract that handles sent tokens and ether with
// owner access control with optional one-time key rotation
// that locks contract functionality.
// ERC20 interface
contract ERC20Token {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract Owned {
address public owner = msg.sender;
bool public locked;
bytes32 private key;
// mapping of used keys
mapping(bytes32 => bool) used;
// require seed (pre-image) and new key modifier
modifier authorize(string secret, bytes32 newKey) {
if (locked) {
require(digest(secret) == key && !used[newKey]);
key = newKey;
// track used keys
if (newKey != 0) used[newKey] = true;
else locked = false;
}
_;
}
// only when unlocked modifier
modifier onlyWhenUnlocked {
require(!locked);
_;
}
// only when locked modifier
modifier onlyWhenLocked {
require(locked);
_;
}
// only owner modifier
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// MARK public view functions
/// @dev createKey - create key off-chain
/// @param _seed secret used to create the key (back this up!!!)
function createKey(
string _seed
) public pure returns(bytes32) {
return digest(_seed);
}
// MARK public functions
/// @dev changeOwner - change ownership of the contract
/// @param _newOwner new owner address
/// @param _seed secret for current key to unlock
/// @param _newKey new key computed from a new seed
function changeOwner(
address _newOwner,
string _seed,
bytes32 _newKey
) public onlyOwner authorize(_seed, _newKey) {
owner = _newOwner;
}
/// @dev lock - lock the contract and functions with a key
/// @param _key computed key via createKey function
function lock(
bytes32 _key
) public onlyOwner onlyWhenUnlocked {
require(_key != 0 && !used[_key]);
used[_key] = true;
locked = true;
key = _key;
}
/// @dev changeKey - change the key that locks contract functionality
/// @param _seed secret for current key to unlock
/// @param _newKey new key computed from a new seed
function changeKey(
string _seed,
bytes32 _newKey
) public onlyOwner onlyWhenLocked authorize(_seed, _newKey) returns(bool) {
require(_newKey != 0);
return true;
}
/// @dev unlock - unlock the contract with the seed for the current key
/// @param _seed secret for current key to unlock
function unlock(
string _seed
) public onlyOwner onlyWhenLocked authorize(_seed, 0) returns(bool) {
return true;
}
function kill(
string _seed
) public onlyOwner authorize(_seed, 0) {
selfdestruct(owner);
}
// MARK internal functions
/// @dev digest - internal hash function
/// @param _seed secret to compute the key
function digest(
string _seed
) internal pure returns(bytes32) {
return keccak256(keccak256(_seed), bytes(_seed).length);
}
}
contract SecureWallet is Owned {
uint public sweepGasLimit = 25000; // gas limit to prevent out of gas exceptions
uint index; // registered token index
// registered tokens
mapping(uint => address) tokens;
// events
event RegisterToken(uint id, address _token);
event UnregisterToken(address _token);
event Approved(address _token, address _tokenOwner, address _spender, uint _value);
event TransferToken(address _token, address _from, address _to, uint value);
// accept ether sent to contract
function() public payable {
require(msg.value > 0);
}
// MARK public view functions
/// @dev tokenBalance - constanct lookup of contract's token balance
/// @param _tokenId index of registered token
function tokenBalance(
uint _tokenId
) public view returns(address tokenAddress, uint balance) {
ERC20Token token = ERC20Token(tokens[_tokenId]);
return (tokens[_tokenId], token.balanceOf(this));
}
// MARK public functions
/// @dev changeSweepGasLimit - change the gas limit to break out of out of gas exceptions
/// @param _limit gas limit to set for sweep function
function changeSweepGasLimit(uint _limit) public onlyOwner {
sweepGasLimit = _limit;
}
/// @dev registerToken - register a token that the contract owns
/// @param _token address of token contract
function registerToken(address _token) public onlyOwner {
tokens[index] = _token;
emit RegisterToken(index, _token);
index++;
}
/// @dev unregisterToken - unregister a token assigned to the contract
/// @param _tokenId index of registered token address
function unregisterToken(uint _tokenId) public onlyOwner {
emit UnregisterToken(tokens[_tokenId]);
delete tokens[_tokenId];
}
/// @dev approve - approve a spender to spend tokens on behalf of the contract
/// @param _tokenId index of registered token address
/// @param _spender address of spender
/// @param _value approved amount for spender to spend
/// @param _seed secret for current key to unlock
/// @param _newKey new key computed from a new secret seed
function approve(
uint _tokenId,
address _spender,
uint _value,
string _seed,
bytes32 _newKey
) public onlyOwner authorize(_seed, _newKey) {
ERC20Token token = ERC20Token(tokens[_tokenId]);
// call token contract's approve function
emit Approved(tokens[_tokenId], this, _spender, _value);
require(token.approve(_spender, _value));
}
/// @dev transferToken - transfer tokens from contract
/// @param _tokenId index of registered token address
/// @param _to address of token recipient, defaults to owner
/// @param _value token amount to send to the recipient, defaults to contract token balance
/// @param _seed secret for current key to unlock
/// @param _newKey new key computed from a new secret seed
function transferToken(
uint _tokenId,
address _to,
uint _value,
string _seed,
bytes32 _newKey
) public onlyOwner authorize(_seed, _newKey) {
if (_to == 0) _to = owner;
// get token balance
ERC20Token token = ERC20Token(tokens[_tokenId]);
uint balance = token.balanceOf(this);
// check value to send
if (_value > balance || _value == 0) _value = balance;
require(_value > 0);
// transfer
emit TransferToken(token, this, _to, _value);
require(token.transfer(_to, _value));
}
/// @dev transferEther - transfer ether from contract to a recipient
/// @param _to address of token recipient, defaults to owner
/// @param _value amount of ether to withdraw, defaults to contract balance
/// @param _seed secret for current key to unlock
/// @param _newKey new key computed from a new secret seed
function transferEther(
address _to,
uint _value,
string _seed,
bytes32 _newKey
) public onlyOwner authorize(_seed, _newKey) {
// default to owner
if (_to == 0) _to = owner;
uint balance = address(this).balance;
// check value to send
if (_value > balance || _value == 0) _value = balance;
require(_value > 0);
require(_to.send(_value));
}
/// @dev sweep - withdraw all tokens and ether from contract to a recipient
/// @param _to address of token recipient
/// @param _allTokens flag to sweep all tokens
/// @param _allEther flag to sweep all ether
/// @param _seed secret for current key to unlock
/// @param _newKey new key computed from a new secret seed
function sweep(
address _to,
bool _allTokens,
bool _allEther,
string _seed,
bytes32 _newKey
) public onlyOwner authorize(_seed, _newKey) {
require(_allTokens || _allEther);
if (_to == 0) _to = owner;
uint amount = 0;
if (_allTokens) {
// iterate through tokens to transfer
for (uint i = 0; i < index; i++) {
if (tokens[i] != 0) {
ERC20Token token = ERC20Token(tokens[i]);
amount = token.balanceOf(this);
if (amount > 0) {
// transfer tokens
emit TransferToken(token, this, _to, amount);
require(token.transfer(_to, amount));
}
// break out if we will fail on out of gas
if (gasleft() <= sweepGasLimit) break;
}
}
}
// send ether if applicable
if (_allEther) {
uint balance = address(this).balance;
if (balance > 0) require(_to.send(balance));
}
}
}
|
unregisterToken - unregister a token assigned to the contract _tokenId index of registered token address
|
function unregisterToken(uint _tokenId) public onlyOwner {
emit UnregisterToken(tokens[_tokenId]);
delete tokens[_tokenId];
}
| 5,531,532
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
bool registered;
string name;
address airlineAddress;
}
struct Flight {
string name;
bool registered;
address airline;
uint256 statusCode;
uint256 timestamp;
}
struct Insurance{
address passenger;
uint256 amount;
Flight flight;
}
uint256 private airlineCount = 0;
uint256 private insuranceCount = 0;
bytes32[] private flightKeys = new bytes32[](0); //Array to track the keys of all registered Flights
address[] private insurees = new address[](0); //Array to track all passengers that have purchased insurance
mapping(bytes32=>Flight) private flights; //Mapping for keeping track of flights by flightKeys
mapping(address => Airline) private airlines; //Mapping for keeping track of airlines
mapping(uint => Insurance) private insurances; //Mapping for keeping track of insurances
mapping(address => uint256) private payouts; // Mapping for storing insurance refund payouts
mapping(address => uint256) private funds; // Mapping for storing funds
mapping(address => uint256) private authorizedContracts; //Mapping for storing authorizedContracts that can call this contract.
uint256 public constant MAX_INSURANCE_VALUE = 1 ether; //highest value of purchasing flight insurance
uint256 public constant MIN_AIRLINE_FUND = 10 ether; //minimum value for airlines to participate in contract
/********************************************************************************************/
/* EVENT DEFINITIONS & CONSTRUCTOR */
/********************************************************************************************/
event InsureeCredited(address insuree, uint credit, uint total);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier to check whether function was called from authorized contract
*/
modifier isAuthorizedCaller(){
require(authorizedContracts[msg.sender] == 1, "Caller is not authorized");
_;
}
/**
* @dev Modifier to check whether insuree is paying within the accurate range of 0 - 1 ether
*/
modifier accurateInsureePayment(){
require(msg.value > 0 && msg.value <= MAX_INSURANCE_VALUE, "Insuree payment should be between 0 - 1 ether");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/**
* @dev Authorizes an external contract to call this contract
*/
function authorizeCaller(address caller) public view requireContractOwner {
require(authorizedContracts[caller] == 0, "Caller already authorized");
authorizedContracts[caller] == 1;
}
/**
* @dev Deauthorizes an external contract to call this contract
*/
function deauthorizeCaller(address caller) public view requireContractOwner {
require(authorizedContracts[caller] == 1, "Caller not initially authorized");
authorizedContracts[caller] == 0;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
string name,
address airlineAddress
)
external
isAuthorizedCaller
requireIsOperational
{
require(!airlines[airlineAddress].registered, "Airline is already registered");
airlines[airlineAddress] = Airline({name: name, registered: true, airlineAddress: airlineAddress});
airlineCount = airlineCount.add(1);
}
/**
* @dev To get the number of airlines registered
*/
function getAirlineCount() public view returns (uint256) {
return airlineCount;
}
/**
* @dev To check whether the specific airline is registered
*/
function isAirlineRegistered(address wallet) external view returns (bool) {
return airlines[wallet].registered;
}
/**
* @dev To check whether the specific airline meets the minimum funds requirement
*/
function isAirlineFunded(address wallet) external view returns (bool) {
return funds[wallet] >= MIN_AIRLINE_FUND;
}
/**
* @dev To check whether the specific flight is already registered
*/
function isFlightRegistered(string memory name, uint256 timestamp, address airline) public view returns (bool) {
bytes32 id = getFlightKey(airline, name, timestamp);
return flights[id].registered;
}
/**
* @dev To register flights
*/
function registerFlight(string name, uint256 timestamp, address airline) external isAuthorizedCaller {
bool registered = isFlightRegistered(name, timestamp, airline);
require(!registered, "Flight is already registered");
bytes32 id = getFlightKey(airline, name, timestamp);
require(!flights[id].registered, "Flight is already registered.");
flights[id].name = name;
flights[id].registered = true;
flights[id].airline = airline;
flights[id].statusCode = 0;
flights[id].timestamp = timestamp;
flightKeys.push(id);
}
/**
* @dev To get the information about the specific airline (this function can be requested from front-end)
*/
function getFlights() external view returns (string[] memory, address[] memory, uint256[] memory) {
uint l = flightKeys.length;
string[] memory names = new string[](l);
address[] memory airline_addr = new address[](l);
uint256[] memory timestamps = new uint256[](l);
for (uint i = 0; i < l; ++i) {
bytes32 key = flightKeys[i];
names[i] = flights[key].name;
airline_addr[i] = flights[key].airline;
timestamps[i] = flights[key].timestamp;
}
return (names, airline_addr, timestamps);
}
/**
* @dev To check any funds owed to the passenger
*/
function checkFunds(address insuree) external view returns (uint){
return payouts[insuree];
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
string flight,
uint256 timestamp,
address airline,
address insuree
)
external
payable
isAuthorizedCaller
accurateInsureePayment
requireIsOperational
{
bytes32 id = getFlightKey(airline, flight, timestamp);
require(flights[id].registered, "Flight does not exist");
uint insurance_amount = 0;
if(msg.value >= MAX_INSURANCE_VALUE){
insurance_amount = MAX_INSURANCE_VALUE;
} else {
insurance_amount = msg.value;
}
insurances[insuranceCount].flight = flights[id];
insurances[insuranceCount].passenger = insuree;
insurances[insuranceCount].amount = insurance_amount;
insuranceCount = insuranceCount.add(1);
insurees.push(insuree);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
string flight,
uint256 timestamp,
address airline
)
external
requireIsOperational
{
bytes32 id = getFlightKey(airline, flight, timestamp);
for (uint i = 0; i < insurees.length; ++i) {
address insuree = insurances[i].passenger;
bytes32 id2 = getFlightKey(insurances[i].flight.airline, insurances[i].flight.name, insurances[i].flight.timestamp);
if(insurances[i].amount == 0) continue;
if (id == id2) {
uint256 value = insurances[i].amount;
uint256 half = value.div(2);
insurances[i].amount = 0;
uint256 refund = value.add(half);
payouts[insuree] = payouts[insuree].add(refund);
emit InsureeCredited(insuree, refund, payouts[insuree]);
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address insuree
)
external
isAuthorizedCaller
{
uint256 refund = payouts[insuree];
payouts[insuree] = 0;
insuree.transfer(refund);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
address sender
)
public
payable
{
require(msg.value > 0, "Funds must be greater than 0");
funds[sender] = funds[sender].add(msg.value);
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function ()
external
payable
{
require(msg.value > 0, "No funds are not allowed");
fund(msg.sender);
}
}
|
Credits payouts to insurees/
|
function creditInsurees
(
string flight,
uint256 timestamp,
address airline
)
external
requireIsOperational
{
bytes32 id = getFlightKey(airline, flight, timestamp);
for (uint i = 0; i < insurees.length; ++i) {
address insuree = insurances[i].passenger;
bytes32 id2 = getFlightKey(insurances[i].flight.airline, insurances[i].flight.name, insurances[i].flight.timestamp);
if(insurances[i].amount == 0) continue;
if (id == id2) {
uint256 value = insurances[i].amount;
uint256 half = value.div(2);
insurances[i].amount = 0;
uint256 refund = value.add(half);
payouts[insuree] = payouts[insuree].add(refund);
emit InsureeCredited(insuree, refund, payouts[insuree]);
}
}
}
| 1,842,618
|
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
address public addressTeam = 0x04cFbFa64917070d7AEECd20225782240E8976dc;
bool public frozenAccountICO = true;
mapping(address => uint256) balances;
mapping (address => bool) public frozenAccount;
function setFrozenAccountICO(bool _frozenAccountICO) public onlyOwner{
frozenAccountICO = _frozenAccountICO;
}
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
if (msg.sender != owner && msg.sender != addressTeam){
require(!frozenAccountICO);
}
require(!frozenAccount[_to]); // Check if recipient is frozen
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (msg.sender != owner && msg.sender != addressTeam){
require(!frozenAccountICO);
}
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract MahalaCoin is Ownable, MintableToken {
using SafeMath for uint256;
string public constant name = "Mahala Coin";
string public constant symbol = "MHC";
uint32 public constant decimals = 18;
// address public addressTeam;
uint public summTeam;
function MahalaCoin() public {
summTeam = 110000000 * 1 ether;
//Founders and supporters initial Allocations
mint(addressTeam, summTeam);
mint(owner, 70000000 * 1 ether);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function getTotalSupply() public constant returns(uint256){
return totalSupply;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where Contributors can make
* token Contributions and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive. The contract requires a MintableToken that will be
* minted as contributions arrive, note that the crowdsale contract
* must be owner of the token in order to be able to mint it.
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
// totalTokens
uint256 public totalTokens;
// soft cap
uint softcap;
// hard cap
uint hardcap;
MahalaCoin public token;
// balances for softcap
mapping(address => uint) public balances;
// balances for softcap
mapping(address => uint) public balancesToken;
// The token being offered
// start and end timestamps where investments are allowed (both inclusive)
//pre-sale
//start
uint256 public startPreSale;
//end
uint256 public endPreSale;
//ico
//start
uint256 public startIco;
//end
uint256 public endIco;
//token distribution
uint256 public maxPreSale;
uint256 public maxIco;
uint256 public totalPreSale;
uint256 public totalIco;
// how many token units a Contributor gets per wei
uint256 public ratePreSale;
uint256 public rateIco;
// address where funds are collected
address public wallet;
// minimum quantity values
uint256 public minQuanValues;
uint256 public maxQuanValues;
/**
* event for token Procurement logging
* @param contributor who Pledged for the tokens
* @param beneficiary who got the tokens
* @param value weis Contributed for Procurement
* @param amount amount of tokens Procured
*/
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
//soft cap
softcap = 5000 * 1 ether;
hardcap = 20000 * 1 ether;
// min quantity values
minQuanValues = 100000000000000000; //0.1 eth
// max quantity values
maxQuanValues = 22 * 1 ether; //
// start and end timestamps where investments are allowed
//Pre-sale
//start
startPreSale = 1523260800;//09 Apr 2018 08:00:00 +0000
//end
endPreSale = startPreSale + 40 * 1 days;
//ico
//start
startIco = endPreSale;
//end
endIco = startIco + 40 * 1 days;
// rate;
ratePreSale = 462;
rateIco = 231;
// restrictions on amounts during the crowdfunding event stages
maxPreSale = 30000000 * 1 ether;
maxIco = 60000000 * 1 ether;
// address where funds are collected
wallet = 0x04cFbFa64917070d7AEECd20225782240E8976dc;
}
function setratePreSale(uint _ratePreSale) public onlyOwner {
ratePreSale = _ratePreSale;
}
function setrateIco(uint _rateIco) public onlyOwner {
rateIco = _rateIco;
}
// fallback function can be used to Procure tokens
function () external payable {
procureTokens(msg.sender);
}
function createTokenContract() internal returns (MahalaCoin) {
return new MahalaCoin();
}
// low level token Pledge function
function procureTokens(address beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
uint256 backAmount;
require(beneficiary != address(0));
//minimum amount in ETH
require(weiAmount >= minQuanValues);
//maximum amount in ETH
require(weiAmount.add(balances[msg.sender]) <= maxQuanValues);
//hard cap
address _this = this;
require(hardcap > _this.balance);
//Pre-sale
if (now >= startPreSale && now < endPreSale && totalPreSale < maxPreSale){
tokens = weiAmount.mul(ratePreSale);
if (maxPreSale.sub(totalPreSale) <= tokens){
endPreSale = now;
startIco = now;
endIco = startIco + 40 * 1 days;
}
if (maxPreSale.sub(totalPreSale) < tokens){
tokens = maxPreSale.sub(totalPreSale);
weiAmount = tokens.div(ratePreSale);
backAmount = msg.value.sub(weiAmount);
}
totalPreSale = totalPreSale.add(tokens);
}
//ico
if (now >= startIco && now < endIco && totalIco < maxIco){
tokens = weiAmount.mul(rateIco);
if (maxIco.sub(totalIco) < tokens){
tokens = maxIco.sub(totalIco);
weiAmount = tokens.div(rateIco);
backAmount = msg.value.sub(weiAmount);
}
totalIco = totalIco.add(tokens);
}
require(tokens > 0);
balances[msg.sender] = balances[msg.sender].add(msg.value);
token.transfer(msg.sender, tokens);
// balancesToken[msg.sender] = balancesToken[msg.sender].add(tokens);
if (backAmount > 0){
msg.sender.transfer(backAmount);
}
emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens);
}
function refund() public{
address _this = this;
require(_this.balance < softcap && now > endIco);
require(balances[msg.sender] > 0);
uint value = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(value);
}
function transferTokenToMultisig(address _address) public onlyOwner {
address _this = this;
require(_this.balance < softcap && now > endIco);
token.transfer(_address, token.balanceOf(_this));
}
function transferEthToMultisig() public onlyOwner {
address _this = this;
require(_this.balance >= softcap && now > endIco);
wallet.transfer(_this.balance);
token.setFrozenAccountICO(false);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
token.freezeAccount(target, freeze);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
token.mint(target, mintedAmount);
}
}
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
|
function transfer(address _to, uint256 _value) public returns (bool) {
if (msg.sender != owner && msg.sender != addressTeam){
require(!frozenAccountICO);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 1,574,649
|
./partial_match/1/0xF406F7A9046793267bc276908778B29563323996/sources/VisionToken.sol
|
Confirms the transfer of `_quantityToInvest` currency to the contract. currency is ETH Math: if _msgValue was not sufficient then revert currency is ERC20
|
function _collectInvestment(
address payable _from,
uint _quantityToInvest,
uint _msgValue,
bool _refundRemainder
) internal
{
if(address(currency) == address(0))
{
if(_refundRemainder)
{
uint refund = _msgValue.sub(_quantityToInvest);
if(refund > 0)
{
Address.sendValue(msg.sender, refund);
}
}
else
{
require(_quantityToInvest == _msgValue, "INCORRECT_MSG_VALUE");
}
}
else
{
require(_msgValue == 0, "DO_NOT_SEND_ETH");
currency.safeTransferFrom(_from, address(this), _quantityToInvest);
}
}
| 3,562,307
|
./partial_match/3/0x79d196D0a03955704aD722DCfcDa32b26C03cEDD/sources/zzz.sol
|
require(lgeEndTime.add(3 days) < now, "Liquidity generation grace period still ongoing");require(LPGenerationCompleted, "Event not over yet");
|
function emergencyRecoveryAllTokens() public onlyOwner {
require(tokenAddress != address(0), "ERC20: can not zero address");
require(tokenUniswapPair != address(0), "ERC20: can not zero address");
uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this));
LPGenerationCompleted = true;
emit TokenClaimed(msg.sender, tokenBalance);
}
| 5,059,311
|
pragma solidity ^0.6.0;
// import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "../contracts/SmartRentalToken.sol";
//import "../contracts/OwnershipExtension.sol";
import "../contracts/ExtensionInfo.sol";
contract SmartOwnershipToken is ERC20 {
//////////////////////////////////////////////////////////////////////////
address public _owner;
uint256 public val;
uint256 public testval;
//SmartRentalToken private _renterToken;
bool public _renterSet;
//address[] extensions;
string[] extensionsNames;
mapping (string => OwnershipExtension) extensions;
//mapping (string => address) public extensions;
mapping (string => bytes) informations;
bool public status;
//list of param;
function getVal()public view returns (uint256){
return val;
}
function getTestVal()public view returns (uint256){
return testval;
}
function getStatus()public view returns(bool){
return status;
}
constructor(string memory name, string memory symbol)
ERC20(name, symbol)
public
{
_mint(_msgSender(), 1);
_owner = _msgSender();
_renterSet = false;
val = 0;
testval =0;
status =false;
}
function check_preconditions() public returns (bool) {
for (uint j = 0; j < extensionsNames.length; j++){
OwnershipExtension currentExtension = extensions[extensionsNames[j]];
uint len = currentExtension.getnumExtensions();
//(bool a, bytes memory _len) = currentExtension.call("getnumExtensions()");
//uint len = bytesToUint(_len);
for (uint i = 0; i < len; i++){//.getnumExtensions(); i++) {
(string memory _a, bool precond, string memory extensionSignature, uint256 arguments) = currentExtension.getExtensionIndex(i);
//call(abi.encodeWithSignature("getExtensionIndex(uint)", i));
if(precond == true){
// _contract.delegatecall(
// abi.encodeWithSignature(ExtendedFunctions[i]._extensionSignature, _sign)
// );
testval = 2;
if(arguments == 0){
testval = 3;
(status, ) = address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature));
testval = 5;
}else if(arguments == 1){
address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"]));
}else if(arguments == 2){
address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"], informations["parameter2"]));
}else if(arguments == 3){
address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"], informations["parameter2"], informations["parameter3"]));
}
// _contract.delegatecall(abi.encode(ExtendedFunctions[i]._extensionSignature));
}
}
}
return true;
}
/*
function invokeExtension(string memory _signature, uint256 _arguments) public returns (bool){
for (uint j = 0; j < extensions.length; j++){
ExtensionToken currentExtension = extensions[j];
for (uint i = 0; i < currentExtension.getnumExtensions(); i++) {
(string storage _a, bool _b, string storage extensionSignature, uint256 arguments) = currentExtension.getExtensionIndex(i);
if(_signature == extensionSignature && _arguments == arguments){
// _contract.delegatecall(
// abi.encodeWithSignature(ExtendedFunctions[i]._extensionSignature, _sign)
// );
if(_arguments == 0){
extensions[j].delegatecall(abi.encodeWithSignature(extensionSignature));
return true;
}else if(_arguments == 1){
extensions[j].delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"]));
return true;
}else if(_arguments == 2){
extensions[j].delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"], informations["parameter2"]));
return true;
}else if(_arguments == 3){
extensions[j].delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"], informations["parameter2"], informations["parameter3"]));
return true;
}
// _contract.delegatecall(abi.encode(ExtendedFunctions[i]._extensionSignature));
}
}
}
return false;
}
*/
modifier onlyOwner {
require(_msgSender() == _owner, "Not owner call");
_;
}
function getOwner() public view returns (address) {
return _owner;
}
/* function getRentalToken() public view returns (address) {
return address(_renterToken);
}
*/
function hasRenter() public view returns (bool) {
return _renterSet;
}
function getThis() public view returns (address) {
return address(this);
}
/* function startRent(address[] memory rentersList, uint rentTime) public onlyOwner {
require(_renterSet == false || (_renterToken.rentIsValid() == false), "This ownership is already rented");
require(_msgSender() == _owner, "Error: the owner of the contract must start the rent");
if(_renterSet == true && _renterToken.rentIsValid() == false){
_renterToken.burn(1);
_renterSet = false;
}
_renterToken = new SmartRentalToken(name(), symbol());
_renterToken.setRent(rentersList, this, rentTime);
_renterSet = true;
}
function endRentFromRenter() public {
require(_renterSet == true, "The product is not on rent");
require(_msgSender() == _renterToken.mainRenter(), "Request for end must be from main renter");
_renterToken.burn(1);
_renterSet = false;
}
function endRentFromOwner() public onlyOwner{
require(_renterSet == true, "The product is not on rent");
require(_renterToken.rentIsValid() == false, "Rent is not finished yet");
_renterToken.burn(1);
_renterSet = false;
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(_renterSet == false || (_renterToken.rentIsValid() == false), "Error: the item is on rent");
require(_msgSender() == _owner, "Only owner is allowed to make transfer");
_transfer(_msgSender(), recipient, amount);
_owner = recipient;
if(_renterSet == true && _renterToken.rentIsValid() == false){//burn the rent
_renterToken.burn(1);
_renterSet = false;
}
return true;
}*/
function addExtension(string memory extensionName, OwnershipExtension extension) public {
extensionsNames.push(extensionName);
extensions[extensionName] = extension;
}
// event AddedValuesByDelegateCall(uint256 a, uint256 b, bool success);
/* function invokeExtension(address extension, string memory _sign)
public payable
{
//without parameter
//updata list of param;
// return extensions[extensionName].delegatecall(bytes4(keccak256("function1()")));
(bool success, bytes memory result) = extension.delegatecall(
abi.encodeWithSignature("invokeExtension(string)", _sign));
//emit AddedValuesByDelegateCall(a, b, success);
//_renterSet = success;
//res = abi.decode(result, (uint256));
}*/
//TODO : CHECK IMPLEMENTATION
function approve(address spender, uint256 amount) public virtual override returns (bool) {
require(spender == address(0), "sstma");
require(amount == 0, "sstma");
return false;
}
/*
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
// if exist precondition => check
require(_renterSet == false || (_renterToken.rentIsValid() == false), "Error: the item is on rent");
require(_msgSender() == _owner, "Only owner is allowed to make transfer");
require(sender == _owner, "Only owner is allowed to make transfer");
_transfer(sender, recipient, amount);
_owner = recipient;
if(_renterSet == true && _renterToken.rentIsValid() == false){//burn the rent
_renterToken.burn(1);
_renterSet = false;
}
return true;
}
function burn(uint amount) public {
require(_msgSender() == _owner, "Trying to burn illegaly");
require(_renterSet == false || (_renterToken.rentIsValid() == false) || (_renterToken.mainRenter() == _owner), "Asset is on rent, can't burn");
if(_renterSet == true){//burn the rent
_renterToken.burn(1);
_renterSet = false;
}
_burn(_msgSender(), amount); //TODO : CHANGE AMOUNT TO 1
}
*/
////////////////////////////////////////////////////////////////////////////////////////////
}
|
(bool a, bytes memory _len) = currentExtension.call("getnumExtensions()");uint len = bytesToUint(_len);call(abi.encodeWithSignature("getExtensionIndex(uint)", i)); _contract.delegatecall( abi.encodeWithSignature(ExtendedFunctions[i]._extensionSignature, _sign) );
|
function check_preconditions() public returns (bool) {
for (uint j = 0; j < extensionsNames.length; j++){
OwnershipExtension currentExtension = extensions[extensionsNames[j]];
uint len = currentExtension.getnumExtensions();
(string memory _a, bool precond, string memory extensionSignature, uint256 arguments) = currentExtension.getExtensionIndex(i);
if(precond == true){
testval = 2;
if(arguments == 0){
testval = 3;
(status, ) = address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature));
testval = 5;
address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"]));
address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"], informations["parameter2"]));
address(extensions[extensionsNames[j]]).delegatecall(abi.encodeWithSignature(extensionSignature, informations["parameter1"], informations["parameter2"], informations["parameter3"]));
}
}
}
return true;
| 1,783,899
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: Account
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
// Part: Actions
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
// Part: ICallee
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// Part: ISoloMargin
interface ISoloMargin {
struct OperatorArg {
address operator1;
bool trusted;
}
function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external;
function getIsGlobalOperator(address operator1) external view returns (bool);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter) external;
function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId) external view returns (address);
function getMarketInterestSetter(uint256 marketId) external view returns (address);
function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory);
function getNumMarkets() external view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) external;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external;
function getIsLocalOperator(address owner, address operator1) external view returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory);
function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external;
function getMarginRatio() external view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) external view returns (bool);
function getRiskParams() external view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
external
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function renounceOwnership() external;
function getMinBorrowedValue() external view returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) external;
function getMarketPrice(uint256 marketId) external view returns (address);
function owner() external view returns (address);
function isOwner() external view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) external;
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
function getMarketWithInfo(uint256 marketId)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) external;
function getLiquidationSpread() external view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account) external view returns (uint8);
function getEarningsRate() external view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle) external;
function getRiskLimits() external view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId) external view returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) external;
function ownerSetGlobalOperator(address operator1, bool approved) external;
function transferOwnership(address newOwner) external;
function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value
memory);
function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory);
}
// Part: IUni
interface IUni{
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Part: InterestRateModel
interface InterestRateModel {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256, uint256);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Address
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/IERC20
/**
* @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);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Math
/**
* @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);
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeMath
/**
* @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;
}
}
// Part: Types
// Part: iearn-finance/yearn-vaults@0.4.2-1/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: CTokenI
interface CTokenI {
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function accrualBlockNumber() external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function interestRateModel() external view returns (InterestRateModel);
function totalReserves() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function totalBorrows() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// Part: DydxFlashloanBase
contract DydxFlashloanBase {
using SafeMath for uint256;
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// Part: IWETH
interface IWETH is IERC20 {
function deposit() external payable;
function decimals() external view returns (uint256);
function withdraw(uint256) external;
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeERC20
/**
* @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");
}
}
}
// Part: iearn-finance/yearn-vaults@0.4.2-1/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: CEtherI
interface CEtherI is CTokenI {
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function liquidateBorrow(address borrower, CTokenI cTokenCollateral) external payable;
function borrow(uint borrowAmount) external returns (uint);
function mint() external payable;
function repayBorrow() external payable;
}
// Part: ComptrollerI
interface ComptrollerI {
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address cToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address cToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address cToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address cToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address cToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address cToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address cToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
/*** Comp claims ****/
function claimComp(address holder) external;
function claimComp(address holder, CTokenI[] memory cTokens) external;
function markets(address ctoken)
external
view
returns (
bool,
uint256,
bool
);
function compSpeeds(address ctoken) external view returns (uint256);
}
// Part: iearn-finance/yearn-vaults@0.4.2-1/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.2";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
/********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/YearnV2-Generic-Lev-Comp-Farm/tree/042weth
* v0.4.2
*
********************* */
contract Strategy is BaseStrategy, DydxFlashloanBase, ICallee {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
//Flash Loan Providers
address private constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
// Comptroller address for compound.finance
ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
//Only three tokens we use
address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
CEtherI public cToken;
//address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
//Operating variables
uint256 public collateralTarget = 0.73 ether; // 73%
uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13
uint256 public minWant; // Default is 0. Only lend if we have enough want to be worth it. Can be set to non-zero
uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest
//To deactivate flash loan provider if needed
bool public DyDxActive = true;
bool public forceMigrate; // default is false
uint256 public dyDxMarketId;
//we need to receive eth
receive() external payable{
}
constructor(address _vault, address _cToken) public BaseStrategy(_vault) {
cToken = CEtherI(address(_cToken));
require(address(want) == weth);
//pre-set approvals
IERC20(comp).safeApprove(uniswapRouter, type(uint256).max);
want.safeApprove(SOLO, type(uint256).max);
// You can set these parameters on deployment to whatever you want
maxReportDelay = 86400; // once per 24 hours
profitFactor = 100; // multiple before triggering harvest
_setMarketIdFromTokenAddress();
}
function name() external override view returns (string memory){
return "StrategyGenericLevCompFarmWeth";
}
/*
* Control Functions
*/
function setDyDx(bool _dydx) external management {
DyDxActive = _dydx;
}
function setForceMigrate(bool _force) external onlyGovernance {
forceMigrate = _force;
}
function setMinCompToSell(uint256 _minCompToSell) external management {
minCompToSell = _minCompToSell;
}
function setMinWant(uint256 _minWant) external management {
minWant = _minWant;
}
function setCollateralTarget(uint256 _collateralTarget) external management {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
require(collateralFactorMantissa > _collateralTarget);
collateralTarget = _collateralTarget;
}
function wantBalance() internal view returns(uint256){
return want.balanceOf(address(this));
}
/*
* Base External Facing Functions
*/
/*
* An accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of want tokens.
*/
function estimatedTotalAssets() public override view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 _claimableComp = predictCompAccrued();
uint256 currentComp = IERC20(comp).balanceOf(address(this));
uint256 estimatedWant;
if(currentComp > 0){
// Use touch price. it doesnt matter if we are wrong as this is not used for decision making
address[] memory path = new address[](2);
path[0] = comp;
path[1] = weth;
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_claimableComp.add(currentComp), path);
estimatedWant = amounts[amounts.length - 1];
}
uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist
return wantBalance().add(address(this).balance).add(deposits).add(conservativeWant).sub(borrows);
}
//predicts our profit at next report
function expectedReturn() public view returns (uint256) {
uint256 estimateAssets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimateAssets) {
return 0;
} else {
return estimateAssets - debt;
}
}
/*
* Provide a signal to the keeper that `tend()` should be called.
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
* tendTrigger should be called with same gasCost as harvestTrigger
*/
function tendTrigger(uint256 gasCost) public override view returns (bool) {
if (harvestTrigger(gasCost)) {
//harvest takes priority
return false;
}
return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone;
}
/*****************
* Public non-base function
******************/
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256) {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 borrrowRate = cToken.borrowRatePerBlock();
uint256 supplyRate = cToken.supplyRatePerBlock();
uint256 collateralisedDeposit = deposits.mul(collateralFactorMantissa).div(1e18);
uint256 denom1 = borrows.mul(borrrowRate);
uint256 denom2 = collateralisedDeposit.mul(supplyRate);
if (denom2 >= denom1) {
return type(uint256).max;
} else {
uint256 numer = collateralisedDeposit.sub(borrows);
uint256 denom = denom1 - denom2;
//minus 1 for this block
return numer.mul(1e18).div(denom);
}
}
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits == 0) {
return 0; // should be impossible to have 0 balance and positive comp accrued
}
//comp speed is amount to borrow or deposit (so half the total distribution for want)
uint256 distributionPerBlock = compound.compSpeeds(address(cToken));
uint256 totalBorrow = cToken.totalBorrows();
//total supply needs to be echanged to underlying using exchange rate
uint256 totalSupplyCtoken = cToken.totalSupply();
uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);
uint256 blockShareSupply = 0;
if(totalSupply > 0){
blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply);
}
uint256 blockShareBorrow = 0;
if(totalBorrow > 0){
blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow);
}
//how much we expect to earn per block
uint256 blockShare = blockShareSupply.add(blockShareBorrow);
//last time we ran harvest
uint256 lastReport = vault.strategies(address(this)).lastReport;
uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block
return blocksSinceLast.mul(blockShare);
}
//Returns the current position
//WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between
//cToken is very active so not normally an issue.
function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) {
(, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this));
borrows = borrowBalance;
deposits = ctokenBalance.mul(exchangeRate).div(1e18);
}
//statechanging version
function getLivePosition() public returns (uint256 deposits, uint256 borrows) {
deposits = cToken.balanceOfUnderlying(address(this));
//we can use non state changing now because we updated state with balanceOfUnderlying call
borrows = cToken.borrowBalanceStored(address(this));
}
//Same warning as above
function netBalanceLent() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
/***********
* internal core logic
*********** */
/*
* A core method.
* Called at beggining of harvest before providing report to owner
* 1 - claim accrued comp
* 2 - if enough to be worth it we sell
* 3 - because we lose money on our loans we need to offset profit from comp.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
) {
_profit = 0;
_loss = 0; //for clarity. also reduces bytesize
if (cToken.balanceOf(address(this)) == 0) {
uint256 wantBal = address(this).balance.add(wantBalance());
//no position to harvest
//but we may have some debt to return
//it is too expensive to free more debt in this method so we do it in adjust position
_debtPayment = Math.min(wantBal, _debtOutstanding);
if(wantBal > 0){
IWETH(weth).deposit{value: wantBal}();
}
return (_profit, _loss, _debtPayment);
}
(uint256 deposits, uint256 borrows) = getLivePosition();
//claim comp accrued
_claimComp();
//sell comp
_disposeOfComp();
uint256 wantBal = address(this).balance.add(wantBalance());
uint256 investedBalance = deposits.sub(borrows);
uint256 balance = investedBalance.add(wantBal);
uint256 debt = vault.strategies(address(this)).totalDebt;
//Balance - Total Debt is profit
if (balance > debt) {
_profit = balance - debt;
if (wantBal < _profit) {
//all reserve is profit
_profit = wantBal;
} else if (wantBal > _profit.add(_debtOutstanding)){
_debtPayment = _debtOutstanding;
}else{
_debtPayment = wantBal - _profit;
}
} else {
//we will lose money until we claim comp then we will make money
//this has an unintended side effect of slowly lowering our total debt allowed
_loss = debt - balance;
_debtPayment = Math.min(wantBal, _debtOutstanding);
}
uint256 bal = address(this).balance;
if(bal > 0){
IWETH(weth).deposit{value: bal}();
}
}
/*
* Second core function. Happens after report call.
*
* Similar to deposit function from V1 strategy
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
//withdraw all weth
uint256 _wantBal = wantBalance();
if(_wantBal > 0){
IWETH(weth).withdraw(_wantBal);
}
//we are spending all our cash unless we have debt outstanding
if(_wantBal < _debtOutstanding){
//this is graceful withdrawal. dont use backup
//we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals
if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(_debtOutstanding - _wantBal);
}
return;
}
(uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true);
//if we are below minimun want change it is not worth doing
//need to be careful in case this pushes to liquidation
if (position > minWant) {
//if dydx is not active we just try our best with basic leverage
if (!DyDxActive) {
uint i = 0;
while(position > 0){
position = position.sub(_noFlashLoan(position, deficit));
if(i >= 6){
break;
}
i++;
}
} else {
//if there is huge position to improve we want to do normal leverage. it is quicker
if (position > want.balanceOf(SOLO)) {
position = position.sub(_noFlashLoan(position, deficit));
}
//flash loan to position
if(position > minWant){
doDyDxFlashLoan(deficit, position);
}
}
}
}
/*************
* Very important function
* Input: amount we want to withdraw and whether we are happy to pay extra for Aave.
* cannot be more than we have
* Returns amount we were able to withdraw. notall if user has some balance left
*
* Deleverage position -> redeem our cTokens
******************** */
function _withdrawSome(uint256 _amount) internal returns (bool notAll) {
(uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false);
//If there is no deficit we dont need to adjust position
//if the position change is tiny do nothing
if (deficit && position > minWant) {
//we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
uint8 i = 0;
//position will equal 0 unless we haven't been able to deleverage enough with flash loan
//if we are not in deficit we dont need to do flash loan
while (position > minWant.add(100)) {
position = position.sub(_noFlashLoan(position, true));
i++;
//A limit set so we don't run out of gas
if (i >= 5) {
notAll = true;
break;
}
}
}
//now withdraw
//if we want too much we just take max
//This part makes sure our withdrawal does not force us into liquidation
(uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition();
uint256 tempColla = collateralTarget;
uint256 reservedAmount = 0;
if(tempColla == 0){
tempColla = 1e15; // 0.001 * 1e18. lower we have issues
}
reservedAmount = borrowBalance.mul(1e18).div(tempColla);
if(depositBalance >= reservedAmount){
uint256 redeemable = depositBalance.sub(reservedAmount);
if (redeemable < _amount) {
cToken.redeemUnderlying(redeemable);
} else {
cToken.redeemUnderlying(_amount);
}
}
if(collateralTarget == 0 && address(this).balance > borrowBalance){
cToken.repayBorrow{value: borrowBalance}();
}
//let's sell some comp if we have more than needed
//flash loan would have sent us comp if we had some accrued so we don't need to call claim comp
_disposeOfComp();
}
/***********
* This is the main logic for calculating how to change our lends and borrows
* Input: balance. The net amount we are going to deposit/withdraw.
* Input: dep. Is it a deposit or withdrawal
* Output: position. The amount we want to change our current borrow position.
* Output: deficit. True if we are reducing position size
*
* For instance deficit =false, position 100 means increase borrowed balance by 100
****** */
function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) {
//we want to use statechanging for safety
(uint256 deposits, uint256 borrows) = getLivePosition();
//When we unwind we end up with the difference between borrow and supply
uint256 unwoundDeposit = deposits.sub(borrows);
//we want to see how close to collateral target we are.
//So we take our unwound deposits and add or remove the balance we are are adding/removing.
//This gives us our desired future undwoundDeposit (desired supply)
uint256 desiredSupply = 0;
if (dep) {
desiredSupply = unwoundDeposit.add(balance);
} else {
if(balance > unwoundDeposit) balance = unwoundDeposit;
desiredSupply = unwoundDeposit.sub(balance);
}
//(ds *c)/(1-c)
uint256 num = desiredSupply.mul(collateralTarget);
uint256 den = uint256(1e18).sub(collateralTarget);
uint256 desiredBorrow = num.div(den);
if (desiredBorrow > 1e5) {
//stop us going right up to the wire
desiredBorrow = desiredBorrow - 1e5;
}
//now we see if we want to add or remove balance
// if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position
if (desiredBorrow < borrows) {
deficit = true;
position = borrows - desiredBorrow; //safemath check done in if statement
} else {
//otherwise we want to increase position
deficit = false;
position = desiredBorrow - borrows;
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amount`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = address(this).balance;
uint256 assets = netBalanceLent().add(_balance);
uint256 debtOutstanding = vault.debtOutstanding();
if(debtOutstanding > assets){
_loss = debtOutstanding - assets;
}
if (assets < _amountNeeded) {
//if we cant afford to withdraw we take all we can
//withdraw all we can
(uint256 deposits, uint256 borrows) = getLivePosition();
//1 token causes rounding error with withdrawUnderlying
if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(deposits.sub(borrows));
}
_amountFreed = Math.min(_amountNeeded, address(this).balance);
} else {
if (_balance < _amountNeeded) {
_withdrawSome(_amountNeeded.sub(_balance));
//overflow error if we return more than asked for
_amountFreed = Math.min(_amountNeeded, address(this).balance);
}else{
_amountFreed = _amountNeeded;
}
}
_balance = address(this).balance;
if(_balance > 0){
IWETH(weth).deposit{value: _balance}();
}
//require for <0.4.3 vaults
require(_amountFreed == _amountNeeded, "NOTALLWITHDRAWN");
}
function _claimComp() internal {
CTokenI[] memory tokens = new CTokenI[](1);
tokens[0] = cToken;
compound.claimComp(address(this), tokens);
}
//sell comp function
function _disposeOfComp() internal {
uint256 _comp = IERC20(comp).balanceOf(address(this));
if (_comp > minCompToSell) {
address[] memory path = new address[](2);
path[0] = comp;
path[1] = weth;
IUni(uniswapRouter).swapExactTokensForETH(_comp, uint256(0), path, address(this), now);
}
}
//lets leave
//if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered
function prepareMigration(address _newStrategy) internal override {
if(!forceMigrate){
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows));
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance < 10_000);
IERC20 _comp = IERC20(comp);
uint _compB = _comp.balanceOf(address(this));
if(_compB > 0){
_comp.safeTransfer(_newStrategy, _compB);
}
}
uint256 bal = address(this).balance;
if(bal > 0){
IWETH(weth).deposit{value: bal}();
}
}
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
//we can use non-state changing because this function is always called after _calculateDesiredPosition
(uint256 lent, uint256 borrowed) = getCurrentPosition();
//if we have nothing borrowed then we can't deleverage any more
if (borrowed == 0 && deficit) {
return 0;
}
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
if (deficit) {
amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
} else {
amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
}
emit Leverage(max, amount, deficit, address(0));
}
//maxDeleverage is how much we want to reduce by
function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = 0;
//collat ration should never be 0. if it is something is very wrong... but just incase
if(collatRatio != 0){
theoreticalLent = borrowed.mul(1e18).div(collatRatio);
}
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
uint256 exchangeRateStored = cToken.exchangeRateStored();
//redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0
//a rounding error means we need another small addition
if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
deleveragedAmount = deleveragedAmount -10;
cToken.redeemUnderlying(deleveragedAmount);
//our borrow has been increased by no more than maxDeleverage
cToken.repayBorrow{value: deleveragedAmount}();
}
}
//maxDeleverage is how much we want to increase by
function _normalLeverage(
uint256 maxLeverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 leveragedAmount) {
uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);
leveragedAmount = theoreticalBorrow.sub(borrowed);
if (leveragedAmount >= maxLeverage) {
leveragedAmount = maxLeverage;
}
if(leveragedAmount > 10){
leveragedAmount = leveragedAmount -10;
cToken.borrow(leveragedAmount);
cToken.mint{value: address(this).balance}();
}
}
//emergency function that we can use to deleverage manually if something is broken
function manualDeleverage(uint256 amount) external management{
require(cToken.redeemUnderlying(amount) == 0);
cToken.repayBorrow{value: amount}();
}
//emergency function that we can use to deleverage manually if something is broken
function manualReleaseWant(uint256 amount) external onlyGovernance{
cToken.redeemUnderlying(amount);
}
function protectedTokens() internal override view returns (address[] memory) {
}
/******************
* Flash loan stuff
****************/
// Flash loan DXDY
// amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {
if(amountDesired == 0){
return 0;
}
uint256 amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
// Not enough want in DyDx. So we take all we can
uint256 amountInSolo = want.balanceOf(SOLO);
if (amountInSolo < amount) {
amount = amountInSolo;
}
bytes memory data = abi.encode(deficit, amount);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(dyDxMarketId, amount);
operations[1] = _getCallAction(
// Encode custom data for callFunction
data
);
operations[2] = _getDepositAction(dyDxMarketId, amount.add(2));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
emit Leverage(amountDesired, amount, deficit, SOLO);
return amount;
}
//returns our current collateralisation ratio. Should be compared with collateralTarget
function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
//DyDx calls this function after doing flash loan
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == SOLO);
require(sender == address(this));
uint256 repayAmount = amount.add(2);
uint256 bal = wantBalance();
require(bal >= amount); // to stop malicious calls
IWETH(weth).withdraw(bal);
//if in deficit we repay amount and then withdraw
if (deficit) {
cToken.repayBorrow{value: amount}();
//if we are withdrawing we take more to cover fee
cToken.redeemUnderlying(repayAmount);
} else {
//reverts on a non zero return
cToken.mint{value: address(this).balance}();
//borrow more to cover fee
// fee is so low for dydx that it does not effect our liquidation risk.
cToken.borrow(repayAmount);
}
IWETH(weth).deposit{value: repayAmount}();
}
// -- Internal Helper functions -- //
function _setMarketIdFromTokenAddress() internal {
ISoloMargin solo = ISoloMargin(SOLO);
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == address(want)) {
dyDxMarketId = i;
return;
}
}
revert();
}
function ethToWant(uint256 _amtInWei) public view override returns (uint256) {
return _amtInWei;
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
(_amountFreed,) = liquidatePosition(vault.debtOutstanding());
IWETH(weth).deposit{value: address(this).balance}();
//we want to revert if we can't liquidateall
if(!forceMigrate) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 position = deposits.sub(borrows);
require(position < minWant);
}
}
function mgtm_check() internal {
require(msg.sender == governance() || msg.sender == strategist);
}
modifier management() {
mgtm_check();
_;
}
}
|
DyDx calls this function after doing flash loanif in deficit we repay amount and then withdrawif we are withdrawing we take more to cover feereverts on a non zero returnborrow more to cover fee fee is so low for dydx that it does not effect our liquidation risk.
|
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == SOLO);
require(sender == address(this));
uint256 repayAmount = amount.add(2);
uint256 bal = wantBalance();
IWETH(weth).withdraw(bal);
if (deficit) {
cToken.redeemUnderlying(repayAmount);
cToken.borrow(repayAmount);
}
}
| 6,921,425
|
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "./libraries/Oracle.sol";
import "./libraries/Volatility.sol";
import "./interfaces/IVolatilityOracle.sol";
/*
#
###
#####
# ####### *###*
### ######### ########
##### ########### ###########
######## ############ ############
######## ########### *##############
########### ######## #################
############ ### #################
############ ##################
############# #################* *#############*
############## ############# #####################################
############### ####****** #######################*
################
################# *############################*
############## ######################################
######## ################* **######*
### ###
*/
contract VolatilityOracle is IVolatilityOracle {
struct Indices {
uint8 read;
uint8 write;
}
/// @inheritdoc IVolatilityOracle
mapping(IUniswapV3Pool => Volatility.PoolMetadata) public cachedPoolMetadata;
/// @inheritdoc IVolatilityOracle
mapping(IUniswapV3Pool => Volatility.FeeGrowthGlobals[25]) public feeGrowthGlobals;
/// @inheritdoc IVolatilityOracle
mapping(IUniswapV3Pool => Indices) public feeGrowthGlobalsIndices;
/// @inheritdoc IVolatilityOracle
function cacheMetadataFor(IUniswapV3Pool pool) external {
Volatility.PoolMetadata memory poolMetadata;
(, , uint16 observationIndex, uint16 observationCardinality, , uint8 feeProtocol, ) = pool.slot0();
poolMetadata.maxSecondsAgo = (Oracle.getMaxSecondsAgo(pool, observationIndex, observationCardinality) * 4) / 5;
uint24 fee = pool.fee();
poolMetadata.gamma0 = fee;
poolMetadata.gamma1 = fee;
if (feeProtocol % 16 != 0) poolMetadata.gamma0 -= fee / (feeProtocol % 16);
if (feeProtocol >> 4 != 0) poolMetadata.gamma1 -= fee / (feeProtocol >> 4);
poolMetadata.tickSpacing = pool.tickSpacing();
cachedPoolMetadata[pool] = poolMetadata;
}
/// @inheritdoc IVolatilityOracle
function lens(IUniswapV3Pool pool) external view returns (uint256[25] memory IV) {
(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0();
Volatility.FeeGrowthGlobals[25] memory feeGrowthGlobal = feeGrowthGlobals[pool];
for (uint8 i = 0; i < 25; i++) {
(IV[i], ) = _estimate24H(pool, sqrtPriceX96, tick, feeGrowthGlobal[i]);
}
}
/// @inheritdoc IVolatilityOracle
function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV) {
(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0();
Volatility.FeeGrowthGlobals[25] storage feeGrowthGlobal = feeGrowthGlobals[pool];
Indices memory idxs = _loadIndicesAndSelectRead(pool, feeGrowthGlobal);
Volatility.FeeGrowthGlobals memory current;
(IV, current) = _estimate24H(pool, sqrtPriceX96, tick, feeGrowthGlobal[idxs.read]);
// Write to storage
if (current.timestamp - 1 hours > feeGrowthGlobal[idxs.write].timestamp) {
idxs.write = (idxs.write + 1) % 25;
feeGrowthGlobals[pool][idxs.write] = current;
}
feeGrowthGlobalsIndices[pool] = idxs;
}
function _estimate24H(
IUniswapV3Pool _pool,
uint160 _sqrtPriceX96,
int24 _tick,
Volatility.FeeGrowthGlobals memory _previous
) private view returns (uint256 IV, Volatility.FeeGrowthGlobals memory current) {
Volatility.PoolMetadata memory poolMetadata = cachedPoolMetadata[_pool];
uint32 secondsAgo = poolMetadata.maxSecondsAgo;
require(secondsAgo >= 1 hours, "Aloe: need more data");
if (secondsAgo > 1 days) secondsAgo = 1 days;
// Throws if secondsAgo == 0
(int24 arithmeticMeanTick, uint160 secondsPerLiquidityX128) = Oracle.consult(_pool, secondsAgo);
current = Volatility.FeeGrowthGlobals(
_pool.feeGrowthGlobal0X128(),
_pool.feeGrowthGlobal1X128(),
uint32(block.timestamp)
);
IV = Volatility.estimate24H(
poolMetadata,
Volatility.PoolData(
_sqrtPriceX96,
_tick,
arithmeticMeanTick,
secondsPerLiquidityX128,
secondsAgo,
_pool.liquidity()
),
_previous,
current
);
}
function _loadIndicesAndSelectRead(IUniswapV3Pool _pool, Volatility.FeeGrowthGlobals[25] storage _feeGrowthGlobal)
private
view
returns (Indices memory)
{
Indices memory idxs = feeGrowthGlobalsIndices[_pool];
uint32 timingError = _timingError(block.timestamp - _feeGrowthGlobal[idxs.read].timestamp);
for (uint8 counter = idxs.read + 1; counter < idxs.read + 25; counter++) {
uint8 newReadIndex = counter % 25;
uint32 newTimingError = _timingError(block.timestamp - _feeGrowthGlobal[newReadIndex].timestamp);
if (newTimingError < timingError) {
idxs.read = newReadIndex;
timingError = newTimingError;
} else break;
}
return idxs;
}
function _timingError(uint256 _age) private pure returns (uint32) {
return uint32(_age < 24 hours ? 24 hours - _age : _age - 24 hours);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./FullMath.sol";
import "./TickMath.sol";
/// @title Oracle
/// @notice Provides functions to integrate with V3 pool oracle
library Oracle {
/**
* @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
* @param pool Address of the pool that we want to observe
* @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
* @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
* @return secondsPerLiquidityX128 The change in seconds per liquidity from (block.timestamp - secondsAgo)
* to block.timestamp
*/
function consult(IUniswapV3Pool pool, uint32 secondsAgo)
internal
view
returns (int24 arithmeticMeanTick, uint160 secondsPerLiquidityX128)
{
require(secondsAgo != 0, "BP");
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = pool.observe(
secondsAgos
);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
arithmeticMeanTick = int24(tickCumulativesDelta / int32(secondsAgo));
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int32(secondsAgo) != 0)) arithmeticMeanTick--;
secondsPerLiquidityX128 = secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];
}
/**
* @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
* @param pool Address of Uniswap V3 pool that we want to observe
* @param observationIndex The observation index from pool.slot0()
* @param observationCardinality The observationCardinality from pool.slot0()
* @dev (, , uint16 observationIndex, uint16 observationCardinality, , , ) = pool.slot0();
* @return secondsAgo The number of seconds ago that the oldest observation was stored
*/
function getMaxSecondsAgo(
IUniswapV3Pool pool,
uint16 observationIndex,
uint16 observationCardinality
) internal view returns (uint32 secondsAgo) {
require(observationCardinality != 0, "NI");
unchecked {
(uint32 observationTimestamp, , , bool initialized) = pool.observations(
(observationIndex + 1) % observationCardinality
);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = pool.observations(0);
}
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "@rari-capital/solmate/src/utils/FixedPointMathLib.sol";
import "./FixedPoint96.sol";
import "./FullMath.sol";
import "./TickMath.sol";
/// @title Volatility
/// @notice Provides functions that use Uniswap v3 to compute price volatility
library Volatility {
struct PoolMetadata {
// the oldest oracle observation that's been populated by the pool
uint32 maxSecondsAgo;
// the overall fee minus the protocol fee for token0, times 1e6
uint24 gamma0;
// the overall fee minus the protocol fee for token1, times 1e6
uint24 gamma1;
// the pool tick spacing
int24 tickSpacing;
}
struct PoolData {
// the current price (from pool.slot0())
uint160 sqrtPriceX96;
// the current tick (from pool.slot0())
int24 currentTick;
// the mean tick over some period (from OracleLibrary.consult(...))
int24 arithmeticMeanTick;
// the mean liquidity over some period (from OracleLibrary.consult(...))
uint160 secondsPerLiquidityX128;
// the number of seconds to look back when getting mean tick & mean liquidity
uint32 oracleLookback;
// the liquidity depth at currentTick (from pool.liquidity())
uint128 tickLiquidity;
}
struct FeeGrowthGlobals {
// the fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
uint256 feeGrowthGlobal0X128;
// the fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
uint256 feeGrowthGlobal1X128;
// the block timestamp at which feeGrowthGlobal0X128 and feeGrowthGlobal1X128 were last updated
uint32 timestamp;
}
/**
* @notice Estimates implied volatility using https://lambert-guillaume.medium.com/on-chain-volatility-and-uniswap-v3-d031b98143d1
* @param metadata The pool's metadata (may be cached)
* @param data A summary of the pool's state from `pool.slot0` `pool.observe` and `pool.liquidity`
* @param a The pool's cumulative feeGrowthGlobals some time in the past
* @param b The pool's cumulative feeGrowthGlobals as of the current block
* @return An estimate of the 24 hour implied volatility scaled by 1e18
*/
function estimate24H(
PoolMetadata memory metadata,
PoolData memory data,
FeeGrowthGlobals memory a,
FeeGrowthGlobals memory b
) internal pure returns (uint256) {
uint256 volumeGamma0Gamma1;
{
uint128 revenue0Gamma1 = computeRevenueGamma(
a.feeGrowthGlobal0X128,
b.feeGrowthGlobal0X128,
data.secondsPerLiquidityX128,
data.oracleLookback,
metadata.gamma1
);
uint128 revenue1Gamma0 = computeRevenueGamma(
a.feeGrowthGlobal1X128,
b.feeGrowthGlobal1X128,
data.secondsPerLiquidityX128,
data.oracleLookback,
metadata.gamma0
);
// This is an approximation. Ideally the fees earned during each swap would be multiplied by the price
// *at that swap*. But for prices simulated with GBM and swap sizes either normally or uniformly distributed,
// the error you get from using geometric mean price is <1% even with high drift and volatility.
volumeGamma0Gamma1 = revenue1Gamma0 + amount0ToAmount1(revenue0Gamma1, data.arithmeticMeanTick);
}
uint128 sqrtTickTVLX32 = uint128(
FixedPointMathLib.sqrt(
computeTickTVLX64(metadata.tickSpacing, data.currentTick, data.sqrtPriceX96, data.tickLiquidity)
)
);
uint48 timeAdjustmentX32 = uint48(
FixedPointMathLib.sqrt((uint256(1 days) << 64) / (b.timestamp - a.timestamp))
);
if (sqrtTickTVLX32 == 0) return 0;
unchecked {
return
(uint256(2e18) * uint256(timeAdjustmentX32) * FixedPointMathLib.sqrt(volumeGamma0Gamma1)) /
sqrtTickTVLX32;
}
}
/**
* @notice Computes an `amount1` that (at `tick`) is equivalent in worth to the provided `amount0`
* @param amount0 The amount of token0 to convert
* @param tick The tick at which the conversion should hold true
* @return amount1 An equivalent amount of token1
*/
function amount0ToAmount1(uint128 amount0, int24 tick) internal pure returns (uint256 amount1) {
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);
uint224 priceX96 = uint224(FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96));
amount1 = FullMath.mulDiv(amount0, priceX96, FixedPoint96.Q96);
}
/**
* @notice Computes pool revenue using feeGrowthGlobal accumulators, then scales it down by a factor of gamma
* @param feeGrowthGlobalAX128 The value of feeGrowthGlobal (either 0 or 1) at time A
* @param feeGrowthGlobalBX128 The value of feeGrowthGlobal (either 0 or 1, but matching) at time B (B > A)
* @param secondsPerLiquidityX128 The difference in the secondsPerLiquidity accumulator from `secondsAgo` seconds ago until now
* @param secondsAgo The oracle lookback period that was used to find `secondsPerLiquidityX128`
* @param gamma The fee factor to scale by
* @return Revenue over the period from `block.timestamp - secondsAgo` to `block.timestamp`, scaled down by a factor of gamma
*/
function computeRevenueGamma(
uint256 feeGrowthGlobalAX128,
uint256 feeGrowthGlobalBX128,
uint160 secondsPerLiquidityX128,
uint32 secondsAgo,
uint24 gamma
) internal pure returns (uint128) {
unchecked {
uint256 temp;
if (feeGrowthGlobalBX128 >= feeGrowthGlobalAX128) {
// feeGrowthGlobal has increased from time A to time B
temp = feeGrowthGlobalBX128 - feeGrowthGlobalAX128;
} else {
// feeGrowthGlobal has overflowed between time A and time B
temp = type(uint256).max - feeGrowthGlobalAX128 + feeGrowthGlobalBX128;
}
temp = FullMath.mulDiv(temp, secondsAgo * gamma, secondsPerLiquidityX128 * 1e6);
return temp > type(uint128).max ? type(uint128).max : uint128(temp);
}
}
/**
* @notice Computes the value of liquidity available at the current tick, denominated in token1
* @param tickSpacing The pool tick spacing (from pool.tickSpacing())
* @param tick The current tick (from pool.slot0())
* @param sqrtPriceX96 The current price (from pool.slot0())
* @param liquidity The liquidity depth at currentTick (from pool.liquidity())
*/
function computeTickTVLX64(
int24 tickSpacing,
int24 tick,
uint160 sqrtPriceX96,
uint128 liquidity
) internal pure returns (uint256 tickTVL) {
tick = TickMath.floor(tick, tickSpacing);
// both value0 and value1 fit in uint192
(uint256 value0, uint256 value1) = _getValuesOfLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tick),
TickMath.getSqrtRatioAtTick(tick + tickSpacing),
liquidity
);
tickTVL = (value0 + value1) << 64;
}
/**
* @notice Computes the value of the liquidity in terms of token1
* @dev Each return value can fit in a uint192 if necessary
* @param sqrtRatioX96 A sqrt price representing the current pool prices
* @param sqrtRatioAX96 A sqrt price representing the lower tick boundary
* @param sqrtRatioBX96 A sqrt price representing the upper tick boundary
* @param liquidity The liquidity being valued
* @return value0 The value of amount0 underlying `liquidity`, in terms of token1
* @return value1 The amount of token1
*/
function _getValuesOfLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) private pure returns (uint256 value0, uint256 value1) {
assert(sqrtRatioAX96 <= sqrtRatioX96 && sqrtRatioX96 <= sqrtRatioBX96);
unchecked {
uint224 numerator = uint224(FullMath.mulDiv(sqrtRatioX96, sqrtRatioBX96 - sqrtRatioX96, FixedPoint96.Q96));
value0 = FullMath.mulDiv(liquidity, numerator, sqrtRatioBX96);
value1 = FullMath.mulDiv(liquidity, sqrtRatioX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
interface IVolatilityOracle {
/**
* @notice Accesses the most recently stored metadata for a given Uniswap pool
* @dev These values may or may not have been initialized and may or may not be
* up to date. `tickSpacing` will be non-zero if they've been initialized.
* @param pool The Uniswap pool for which metadata should be retrieved
* @return maxSecondsAgo The age of the oldest observation in the pool's oracle
* @return gamma0 The pool fee minus the protocol fee on token0, scaled by 1e6
* @return gamma1 The pool fee minus the protocol fee on token1, scaled by 1e6
* @return tickSpacing The pool's tick spacing
*/
function cachedPoolMetadata(IUniswapV3Pool pool)
external
view
returns (
uint32 maxSecondsAgo,
uint24 gamma0,
uint24 gamma1,
int24 tickSpacing
);
/**
* @notice Accesses any of the 25 most recently stored fee growth structs
* @dev The full array (idx=0,1,2...24) has data that spans *at least* 24 hours
* @param pool The Uniswap pool for which fee growth should be retrieved
* @param idx The index into the storage array
* @return feeGrowthGlobal0X128 Total pool revenue in token0, as of timestamp
* @return feeGrowthGlobal1X128 Total pool revenue in token1, as of timestamp
* @return timestamp The time at which snapshot was taken and stored
*/
function feeGrowthGlobals(IUniswapV3Pool pool, uint256 idx)
external
view
returns (
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint32 timestamp
);
/**
* @notice Returns indices that the contract will use to access `feeGrowthGlobals`
* @param pool The Uniswap pool for which array indices should be fetched
* @return read The index that was closest to 24 hours old last time `estimate24H` was called
* @return write The index that was written to last time `estimate24H` was called
*/
function feeGrowthGlobalsIndices(IUniswapV3Pool pool) external view returns (uint8 read, uint8 write);
/**
* @notice Updates cached metadata for a Uniswap pool. Must be called at least once
* in order for volatility to be determined. Should also be called whenever
* protocol fee changes
* @param pool The Uniswap pool to poke
*/
function cacheMetadataFor(IUniswapV3Pool pool) external;
/**
* @notice Provides multiple estimates of IV using all stored `feeGrowthGlobals` entries for `pool`
* @dev This is not meant to be used on-chain, and it doesn't contribute to the oracle's knowledge.
* Please use `estimate24H` instead.
* @param pool The pool to use for volatility estimate
* @return IV The array of volatility estimates, scaled by 1e18
*/
function lens(IUniswapV3Pool pool) external returns (uint256[25] memory IV);
/**
* @notice Estimates 24-hour implied volatility for a Uniswap pool.
* @param pool The pool to use for volatility estimate
* @return IV The estimated volatility, scaled by 1e18
*/
function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// Handle division by zero
require(denominator != 0);
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Short circuit 256 by 256 division
// This saves gas when a * b is small, at the cost of making the
// large case a bit more expensive. Depending on your use case you
// may want to remove this short circuit and always go through the
// 512 bit path.
if (prod1 == 0) {
assembly {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Handle overflow, the result must be < 2**256
require(prod1 < denominator);
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Note mulmod(_, _, 0) == 0
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
unchecked {
// https://ethereum.stackexchange.com/a/96646
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
// If denominator is zero the inverse starts with 2
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// If denominator is zero, inv is now 128
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(uint24(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
unchecked {
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
/// @notice Rounds down to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the floored tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24
function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod >= 0) return tick - mod;
return tick - mod - tickSpacing;
}
}
/// @notice Rounds up to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the ceiled tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24
function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod > 0) return tick - mod + tickSpacing;
return tick - mod;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Modified from Dappsys V2 (https://github.com/dapp-org/dappsys-v2/blob/main/src/math.sol)
/// and ABDK (https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol)
library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
COMMON BASE UNITS
//////////////////////////////////////////////////////////////*/
uint256 internal constant YAD = 1e8;
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
uint256 internal constant RAD = 1e45;
/*///////////////////////////////////////////////////////////////
FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
if or(
// Revert if y is zero to ensure we don't divide by zero below.
iszero(y),
// Equivalent to require(x == 0 || (x * baseUnit) / x == baseUnit)
iszero(or(iszero(x), eq(div(z, x), baseUnit)))
) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function fpow(
uint256 x,
uint256 n,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := baseUnit
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := baseUnit
}
default {
z := x
}
let half := div(baseUnit, 2)
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, baseUnit)
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, baseUnit)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) return 0;
result = 1;
uint256 xAux = x;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) result <<= 1;
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
uint256 roundedDownResult = x / result;
if (result > roundedDownResult) result = roundedDownResult;
}
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x > y ? x : y;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
|
metadata The pool's metadata (may be cached) data A summary of the pool's state from `pool.slot0` `pool.observe` and `pool.liquidity` a The pool's cumulative feeGrowthGlobals some time in the past b The pool's cumulative feeGrowthGlobals as of the current block return An estimate of the 24 hour implied volatility scaled by 1e18/ This is an approximation. Ideally the fees earned during each swap would be multiplied by the price at that swap. But for prices simulated with GBM and swap sizes either normally or uniformly distributed, the error you get from using geometric mean price is <1% even with high drift and volatility.
|
function estimate24H(
PoolMetadata memory metadata,
PoolData memory data,
FeeGrowthGlobals memory a,
FeeGrowthGlobals memory b
) internal pure returns (uint256) {
uint256 volumeGamma0Gamma1;
{
uint128 revenue0Gamma1 = computeRevenueGamma(
a.feeGrowthGlobal0X128,
b.feeGrowthGlobal0X128,
data.secondsPerLiquidityX128,
data.oracleLookback,
metadata.gamma1
);
uint128 revenue1Gamma0 = computeRevenueGamma(
a.feeGrowthGlobal1X128,
b.feeGrowthGlobal1X128,
data.secondsPerLiquidityX128,
data.oracleLookback,
metadata.gamma0
);
volumeGamma0Gamma1 = revenue1Gamma0 + amount0ToAmount1(revenue0Gamma1, data.arithmeticMeanTick);
}
uint128 sqrtTickTVLX32 = uint128(
FixedPointMathLib.sqrt(
computeTickTVLX64(metadata.tickSpacing, data.currentTick, data.sqrtPriceX96, data.tickLiquidity)
)
);
uint48 timeAdjustmentX32 = uint48(
FixedPointMathLib.sqrt((uint256(1 days) << 64) / (b.timestamp - a.timestamp))
);
if (sqrtTickTVLX32 == 0) return 0;
unchecked {
return
(uint256(2e18) * uint256(timeAdjustmentX32) * FixedPointMathLib.sqrt(volumeGamma0Gamma1)) /
sqrtTickTVLX32;
}
}
| 6,370,009
|
pragma solidity ^0.5.0;
import "./UsingTellor.sol";
/**
* @title Optimistic
* This contracts allows users to use Tellor as a fallback oracle. It allows two parties to centrally
* enter the data used to settle a contract but allows either party to dispute the data. If a dispute is
* initiated their contract will settle to Tellor's value.
*/
contract Optimistic is UsingTellor {
mapping(uint256 => bool) public isValue; //mapping for timestamp to bool where it's true if the value as been set
mapping(uint256 => uint256) valuesByTimestamp; //mapping of timestamp to value
mapping(uint256 => bool) public disputedValues; //maping of timestamp to bool where it's true if the value has been disputed
mapping(uint256 => uint256[]) public requestIdsIncluded; //mapping of timestamp to requestsId's to include
// struct infoForTimestamp {
// bool isValue;
// uint valuesByTimestamp;
// bool disputedValues;
// uint[] requestIdsIncluded;
// }
// mapping(uint => infoForTimestamp) public infoForTimestamps;//mapping timestampt to InfoForTimestamp struct
uint256[] timestamps; //timestamps with values
uint256[] requestIds;
uint256[] disputedValuesArray;
uint256 public granularity;
uint256 public disputeFee; //In Tributes
uint256 public disputePeriod;
event NewValueSet(uint256 indexed _timestamp, uint256 _value);
event ValueDisputed(address _disputer, uint256 _timestamp, uint256 _value);
event TellorValuePlaced(uint256 _timestamp, uint256 _value);
/*Constructor*/
/**
* @dev This constructor function is used to pass variables to the UserContract's constructor and set several variables
* the variables for the Optimistic.sol constructor come for the Reader.Constructor function.
* @param _userContract address for UserContract
* @param _disputeFeeRequired the fee to dispute the optimistic price(price sumbitted by known trusted party)
* @param _disputePeriod is the time frame a value can be disputed after being imputed
* @param _requestIds are the requests Id's on the Tellor System corresponding to the data types used on this contract.
* It is recommended to use several requestId's that pull from several API's. If requestsId's don't exist in the Tellor
* System be sure to create some.
* @param _granularity is the amount of decimals desired on the requested value
*/
constructor(address _userContract, uint256 _disputeFeeRequired, uint256 _disputePeriod, uint256[] memory _requestIds, uint256 _granularity)
public
UsingTellor(_userContract)
{
disputeFee = _disputeFeeRequired;
disputePeriod = _disputePeriod;
granularity = _granularity;
requestIds = _requestIds;
}
/*Functions*/
/**
* @dev allows contract owner, a centralized party to enter value
* @param _timestamp is the timestamp for the value
* @param _value is the value for the timestamp specified
*/
function setValue(uint256 _timestamp, uint256 _value) external {
//Only allows owner to set value
require(msg.sender == owner, "Sender is not owner");
//Checks that no value has already been set for the timestamp
require(getIsValue(_timestamp) == false, "Timestamp is already set");
//sets timestamp
valuesByTimestamp[_timestamp] = _value;
//sets isValue to true once value is set
isValue[_timestamp] = true;
//adds timestamp to the timestamps array
timestamps.push(_timestamp);
//lets the network know a new timestamp and value have been added
emit NewValueSet(_timestamp, _value);
}
/**
* @dev allows user to initiate dispute on the value of the specified timestamp
* @param _timestamp is the timestamp for the value to be disputed
*/
function disputeOptimisticValue(uint256 _timestamp) external payable {
require(msg.value >= disputeFee, "Value is below dispute fee");
//require that isValue for the timestamp being disputed to exist/be true
require(isValue[_timestamp], "Value for the timestamp being disputed doesn't exist");
// assert disputePeriod is still open
require(now - (now % granularity) <= _timestamp + disputePeriod, "Dispute period is closed");
//set the disputValues for the disputed timestamp to true
disputedValues[_timestamp] = true;
//add the disputed timestamp to the diputedValues array
disputedValuesArray.push(_timestamp);
emit ValueDisputed(msg.sender, _timestamp, valuesByTimestamp[_timestamp]);
}
/**
* @dev This function gets the Tellor requestIds values for the disputed timestamp. It averages the values on the
* requestsIds and replaces the value set by the contract owner, centralized party.
* @param _timestamp to get Tellor data from
* @return uint of new value and true if it was able to get Tellor data
*/
function getTellorValues(uint256 _timestamp) public returns (uint256 _value, bool _didGet) {
//We need to get the tellor value within the granularity. If no Tellor value is available...what then? Simply put no Value?
//No basically, the dispute period for anyValue is within the granularity
TellorMaster _tellor = TellorMaster(tellorUserContract.tellorStorageAddress());
Tellor _tellorCore = Tellor(tellorUserContract.tellorStorageAddress());
uint256 _retrievedTimestamp;
uint256 _initialBalance = _tellor.balanceOf(address(this)); //Checks the balance of Tellor Tributes on this contract
//Loops through all the Tellor requestsId's initially(in the constructor) associated with this contract data
for (uint256 i = 1; i <= requestIds.length; i++) {
//Get all values for that requestIds' timestamp
//Check if any is after your given timestamp
//If yes, return that value. If no, then request that Id
(_didGet, _value, _retrievedTimestamp) = getFirstVerifiedDataAfter(i, _timestamp);
if (_didGet) {
uint256 _newTime = _retrievedTimestamp - (_retrievedTimestamp % granularity); //why are we using the mod granularity???
//provides the average of the requests Ids' associated with this price feed
uint256 _newValue = (_value + valuesByTimestamp[_newTime] * requestIdsIncluded[_newTime].length) /
(requestIdsIncluded[_newTime].length + 1);
//Add the new timestamp and value (we don't replace???)
valuesByTimestamp[_newTime] = _newValue;
emit TellorValuePlaced(_newTime, _newValue);
//records the requests Ids included on the price average where all prices came from Tellor requests Ids
requestIdsIncluded[_newTime].push(i); //how do we make sure it's not called twice?
//if the value for the newTime does not exist, then push the value, update the isValue to true
//otherwise if the newTime is under dsipute then update the dispute status to false
// ??? should the else be an "and"
if (isValue[_newTime] == false) {
timestamps.push(_newTime);
isValue[_newTime] = true;
emit NewValueSet(_newTime, _value);
} else if (disputedValues[_newTime] == true) {
disputedValues[_newTime] = false;
}
//otherwise request the ID and split the contracts initial tributes balance to equally tip all
//requests Ids associated with this price feed
} else if (_tellor.balanceOf(address(this)) > requestIds.length) {
//Request Id to be mined by adding to it's tip
_tellorCore.addTip(i, _initialBalance / requestIds.length);
}
}
}
/**
* @dev Allows the contract owner(Tellor) to withdraw ETH from this contract
*/
function withdrawETH() external {
require(msg.sender == owner, "Sender is not owner");
address(owner).transfer(address(this).balance);
}
/**
* @dev Get the first undisputed value after the timestamp specified. This function is used within the getTellorValues
* but can be used on its own.
* @param _timestamp to search the first undisputed value there after
*/
function getFirstUndisputedValueAfter(uint256 _timestamp) public view returns (bool, uint256, uint256 _timestampRetrieved) {
uint256 _count = timestamps.length;
if (_count > 0) {
for (uint256 i = _count; i > 0; i--) {
if (timestamps[i - 1] >= _timestamp && disputedValues[timestamps[i - 1]] == false) {
_timestampRetrieved = timestamps[i - 1];
}
}
if (_timestampRetrieved > 0) {
return (true, getMyValuesByTimestamp(_timestampRetrieved), _timestampRetrieved);
}
}
return (false, 0, 0);
}
/*Getters*/
/**
* @dev Getter function for the value based on the timestamp specified
* @param _timestamp to retreive value from
*/
function getMyValuesByTimestamp(uint256 _timestamp) public view returns (uint256 value) {
return valuesByTimestamp[_timestamp];
}
/**
* @dev Getter function for the number of RequestIds associated with a timestamp, based on the timestamp specified
* @param _timestamp to retreive number of requestIds
* @return uint count of number of values for the spedified timestamp
*/
function getNumberOfValuesPerTimestamp(uint256 _timestamp) external view returns (uint256) {
return requestIdsIncluded[_timestamp].length;
}
/**
* @dev Checks to if a value exists for the specifived timestamp
* @param _timestamp to verify
* @return ture if it exists
*/
function getIsValue(uint256 _timestamp) public view returns (bool) {
return isValue[_timestamp];
}
/**
* @dev Getter function for latest value available
* @return latest value available
*/
function getCurrentValue() external view returns (uint256) {
require(timestamps.length > 0, "Timestamps' length is 0");
return getMyValuesByTimestamp(timestamps[timestamps.length - 1]);
}
/**
* @dev Getter function for the timestamps available
* @return uint array of timestamps available
*/
function getTimestamps() external view returns (uint256[] memory) {
return timestamps;
}
/**
* @dev Getter function for the requests Ids' from Tellor associated with this price feed
* @return uint array of requests Ids'
*/
function getRequestIds() external view returns (uint256[] memory) {
return requestIds;
}
/**
* @dev Getter function for the requests Ids' from Tellor associated with this price feed
* at the specified timestamp. This only gets populated after a dispute is initiated and the
* function getTellorValues is ran.
* @param _timestamp to retreive the requestIds
* @return uint array of requests Ids' included in the calcluation of the value
*/
function getRequestIdsIncluded(uint256 _timestamp) external view returns (uint256[] memory) {
return requestIdsIncluded[_timestamp];
}
/**
* @dev Getter function for the number of disputed values
* @return uint count of number of values for the spedified timestamp
*/
function getNumberOfDisputedValues() external view returns (uint256) {
return disputedValuesArray.length;
}
/**
* @dev Getter function for all disputed values
* @return the array with all values under dispute
*/
function getDisputedValues() external view returns (uint256[] memory) {
return disputedValuesArray;
}
/**
* @dev This checks if the value for the specified timestamp is under dispute
* @param _timestamp to check if it is under dispute
* @return true if it is under dispute
*/
function isDisputed(uint256 _timestamp) external view returns (bool) {
return disputedValues[_timestamp];
}
/**
* @dev Getter function for the dispute value by index
* @return the value
*/
function getDisputedValueByIndex(uint256 _index) external view returns (uint256) {
return disputedValuesArray[_index];
}
}
|
allows user to initiate dispute on the value of the specified timestamp _timestamp is the timestamp for the value to be disputed/require that isValue for the timestamp being disputed to exist/be true assert disputePeriod is still openset the disputValues for the disputed timestamp to trueadd the disputed timestamp to the diputedValues array
|
function disputeOptimisticValue(uint256 _timestamp) external payable {
require(msg.value >= disputeFee, "Value is below dispute fee");
require(isValue[_timestamp], "Value for the timestamp being disputed doesn't exist");
require(now - (now % granularity) <= _timestamp + disputePeriod, "Dispute period is closed");
disputedValues[_timestamp] = true;
disputedValuesArray.push(_timestamp);
emit ValueDisputed(msg.sender, _timestamp, valuesByTimestamp[_timestamp]);
}
| 12,965,495
|
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
interface IIntegralReader {
struct Parameters {
int256[] bidExponents;
int256[] bidQs;
int256[] askExponents;
int256[] askQs;
}
function getPairParameters(address pair)
external
view
returns (
bool exists,
uint112 reserve0,
uint112 reserve1,
uint112 reference0,
uint112 reference1,
uint256 mintFee,
uint256 burnFee,
uint256 swapFee,
uint32 pairEpoch,
uint32 oracleEpoch,
int256 price,
Parameters memory parameters
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
import 'IERC20.sol';
interface IIntegralERC20 is IERC20 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
interface IReserves {
event Sync(uint112 reserve0, uint112 reserve1);
event Fees(uint256 fee0, uint256 fee1);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 lastTimestamp
);
function getReferences()
external
view
returns (
uint112 reference0,
uint112 reference1,
uint32 epoch
);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
import 'IIntegralERC20.sol';
import 'IReserves.sol';
interface IIntegralPair is IIntegralERC20, IReserves {
event Mint(address indexed sender, address indexed to);
event Burn(address indexed sender, address indexed to);
event Swap(address indexed sender, address indexed to);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
event SetToken0AbsoluteLimit(uint256 limit);
event SetToken1AbsoluteLimit(uint256 limit);
event SetToken0RelativeLimit(uint256 limit);
event SetToken1RelativeLimit(uint256 limit);
event SetPriceDeviationLimit(uint256 limit);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function token0AbsoluteLimit() external view returns (uint256);
function setToken0AbsoluteLimit(uint256 limit) external;
function token1AbsoluteLimit() external view returns (uint256);
function setToken1AbsoluteLimit(uint256 limit) external;
function token0RelativeLimit() external view returns (uint256);
function setToken0RelativeLimit(uint256 limit) external;
function token1RelativeLimit() external view returns (uint256);
function setToken1RelativeLimit(uint256 limit) external;
function priceDeviationLimit() external view returns (uint256);
function setPriceDeviationLimit(uint256 limit) external;
function collect(address to) external;
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to
) external;
function sync() external;
function initialize(
address _token0,
address _token1,
address _oracle,
address _trader
) external;
function syncWithOracle() external;
function fullSync() external;
function getSpotPrice() external view returns (uint256 spotPrice);
function getSwapAmount0In(uint256 amount1Out) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1) external view returns (uint256 depositAmount1In);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
interface IIntegralOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
event PriceUpdateIntervalSet(uint32 interval);
event ParametersSet(uint32 epoch, int256[] bidExponents, int256[] bidQs, int256[] askExponents, int256[] askQs);
function owner() external view returns (address);
function setOwner(address) external;
function epoch() external view returns (uint32);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function getParameters()
external
view
returns (
int256[] memory bidExponents,
int256[] memory bidQs,
int256[] memory askExponents,
int256[] memory askQs
);
function setParameters(
int256[] calldata bidExponents,
int256[] calldata bidQs,
int256[] calldata askExponents,
int256[] calldata askQs
) external;
function price() external view returns (int256);
function priceUpdateInterval() external view returns (uint32);
function updatePrice() external returns (uint32 _epoch);
function setPriceUpdateInterval(uint32 interval) external;
function price0CumulativeLast() external view returns (uint256);
function blockTimestampLast() external view returns (uint32);
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 xBefore,
uint256 yBefore
) external view returns (uint256 xAfter);
function getSpotPrice(uint256 xCurrent, uint256 xBefore) external view returns (uint256 spotPrice);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import 'IIntegralReader.sol';
import 'IIntegralPair.sol';
import 'IIntegralOracle.sol';
contract IntegralReader is IIntegralReader {
function isContract(address addressToCheck) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addressToCheck)
}
return size > 0;
}
function getPairParameters(address pair)
external
view
override
returns (
bool exists,
uint112 reserve0,
uint112 reserve1,
uint112 reference0,
uint112 reference1,
uint256 mintFee,
uint256 burnFee,
uint256 swapFee,
uint32 pairEpoch,
uint32 oracleEpoch,
int256 price,
Parameters memory parameters
)
{
exists = isContract(pair);
if (exists) {
(reserve0, reserve1, ) = IIntegralPair(pair).getReserves();
(reference0, reference1, pairEpoch) = IIntegralPair(pair).getReferences();
mintFee = IIntegralPair(pair).mintFee();
burnFee = IIntegralPair(pair).burnFee();
swapFee = IIntegralPair(pair).swapFee();
address oracle = IIntegralPair(pair).oracle();
oracleEpoch = IIntegralOracle(oracle).epoch();
if (oracleEpoch != pairEpoch) {
reference0 = reserve0;
reference1 = reserve1;
}
price = IIntegralOracle(oracle).price();
{
(
int256[] memory bidExponents,
int256[] memory bidQs,
int256[] memory askExponents,
int256[] memory askQs
) = IIntegralOracle(oracle).getParameters();
parameters = Parameters(bidExponents, bidQs, askExponents, askQs);
}
}
}
}
|
SPDX-License-Identifier: GPL-3.0-or-later Deployed with donations via Gitcoin GR9
|
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
| 345,353
|
./partial_match/1/0x73F6af4495404E3dD076c5C33802532fa394d49E/sources/SHIAInu.sol
|
set minimum tokens required to swap.
|
function setSwapTokenThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapExactAmount = swapTokensAtAmount;
}
| 2,620,779
|
./full_match/5/0x0BdAd0BBbC7E5F9DBF212E5e2D567462F20bBfF1/sources/contracts/Doggyv5.sol
|
unblacklist address; not affected by blacklistRenounced incase team wants to unblacklist v3 pools down the road
|
function unblacklist(address _addr) public onlyOwner {
blacklisted[_addr] = false;
}
| 1,857,163
|
pragma solidity ^0.4.24;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Destructible.sol
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
constructor() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/token/ERC223/ERC223Basic.sol
/**
* @title ERC223Basic extends ERC20 interface and supports ERC223
*/
contract ERC223Basic is ERC20Basic {
function transfer(address _to, uint256 _value, bytes _data) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
}
// File: contracts/token/ERC223/ERC223ReceivingContract.sol
/**
* @title ERC223ReceivingContract contract that will work with ERC223 tokens.
*/
contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) public returns (bool);
}
// File: contracts/Adminable.sol
/**
* @title Adminable
* @dev The Adminable contract has the simple protection logic, and provides admin based access control
*/
contract Adminable is Ownable {
address public admin;
event AdminDesignated(address indexed previousAdmin, address indexed newAdmin);
/**
* @dev Throws if called the non admin.
*/
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
/**
* @dev Throws if called the non owner and non admin.
*/
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || msg.sender == admin);
_;
}
/**
* @dev Designate new admin for the address
* @param _address address The address you want to be a new admin
*/
function designateAdmin(address _address) public onlyOwner {
require(_address != address(0) && _address != owner);
emit AdminDesignated(admin, _address);
admin = _address;
}
}
// File: contracts/Lockable.sol
/**
* @title Lockable
* @dev The Lockable contract has an locks address map, and provides lockable control
* functions, this simplifies the implementation of "lock transfers".
*
*/
contract Lockable is Adminable, ERC20Basic {
using SafeMath for uint256;
// EPOCH TIMESTAMP OF "Tue Sept 24 2019 00:00:00 GMT+0000"
// @see https://www.unixtimestamp.com/index.php
uint public globalUnlockTime = 1569355060;
uint public constant decimals = 18;
event UnLock(address indexed unlocked);
event Lock(address indexed locked, uint until, uint256 value, uint count);
event UpdateGlobalUnlockTime(uint256 epoch);
struct LockMeta {
uint256 value;
uint until;
}
mapping(address => LockMeta[]) internal locksMeta;
mapping(address => bool) locks;
/**
* @dev Lock tokens for the address
* @param _address address The address you want to lock tokens
* @param _days uint The days count you want to lock untill from now
* @param _value uint256 the amount of tokens to be locked
*/
function lock(address _address, uint _days, uint256 _value) onlyOwnerOrAdmin public {
_value = _value*(10**decimals);
require(_value > 0);
require(_days > 0);
require(_address != owner);
require(_address != admin);
uint untilTime = block.timestamp + _days * 1 days;
locks[_address] = true;
// check if we have locks
locksMeta[_address].push(LockMeta(_value, untilTime));
// fire lock event
emit Lock(_address, untilTime, _value, locksMeta[_address].length);
}
/**
* @dev Unlock tokens for the address
* @param _address address The address you want to unlock tokens
*/
function unlock(address _address) onlyOwnerOrAdmin public {
locks[_address] = false;
delete locksMeta[_address];
emit UnLock(_address);
}
/**
* @dev Gets the locked balance of the specified address and time
* @param _owner The address to query the locked balance of.
* @param _time The timestamp seconds to query the locked balance of.
* @return An uint256 representing the locked amount owned by the passed address.
*/
function lockedBalanceOf(address _owner, uint _time) public view returns (uint256) {
LockMeta[] memory locked = locksMeta[_owner];
uint length = locked.length;
// if no locks or even not created (takes bdefault) return 0
if (length == 0) {
return 0;
}
// sum all available locks
uint256 _result = 0;
for (uint i = 0; i < length; i++) {
if (_time <= locked[i].until) {
_result = _result.add(locked[i].value);
}
}
return _result;
}
/**
* @dev Gets the locked balance of the specified address of the current time
* @param _owner The address to query the locked balance of.
* @return An uint256 representing the locked amount owned by the passed address.
*/
function lockedNowBalanceOf(address _owner) public view returns (uint256) {
return this.lockedBalanceOf(_owner, block.timestamp);
}
/**
* @dev Gets the unlocked balance of the specified address and time
* @param _owner The address to query the unlocked balance of.
* @param _time The timestamp seconds to query the unlocked balance of.
* @return An uint256 representing the unlocked amount owned by the passed address.
*/
function unlockedBalanceOf(address _owner, uint _time) public view returns (uint256) {
return this.balanceOf(_owner).sub(lockedBalanceOf(_owner, _time));
}
/**
* @dev Gets the unlocked balance of the specified address of the current time
* @param _owner The address to query the unlocked balance of.
* @return An uint256 representing the unlocked amount owned by the passed address.
*/
function unlockedNowBalanceOf(address _owner) public view returns (uint256) {
return this.unlockedBalanceOf(_owner, block.timestamp);
}
function updateGlobalUnlockTime(uint256 _epoch) public onlyOwnerOrAdmin returns (bool) {
require(_epoch >= 0);
globalUnlockTime = _epoch;
emit UpdateGlobalUnlockTime(_epoch);
// Gives owner the ability to update lockup period for all wallets.
// Owner can pass an epoch timecode into the function to:
// 1. Extend lockup period,
// 2. Unlock all wallets by passing '0' into the function
}
/**
* @dev Throws if the value less than the current unlocked balance of.
*/
modifier onlyUnlocked(uint256 _value) {
if(block.timestamp > globalUnlockTime) {
_;
} else {
if (locks[msg.sender] == true) {
require(this.unlockedNowBalanceOf(msg.sender) >= _value);
}
_;
}
}
/**
* @dev Throws if the value less than the current unlocked balance of the given address.
*/
modifier onlyUnlockedOf(address _address, uint256 _value) {
if(block.timestamp > globalUnlockTime) {
_;
} else {
if (locks[_address] == true) {
require(this.unlockedNowBalanceOf(_address) >= _value);
} else {
}
_;
}
}
}
// File: contracts/StandardLockableToken.sol
/**
* @title StandardLockableToken
*
*/
contract StandardLockableToken is Lockable, /**/ERC223Basic, /*ERC20*/StandardToken {
/**
* @dev Check address is to be a contract based on extcodesize (must be nonzero to be a contract)
* @param _address The address to check.
*/
function isContract(address _address) private constant returns (bool) {
uint256 codeLength;
assembly {
codeLength := extcodesize(_address)
}
return codeLength > 0;
}
/**
* @dev Transfer token for a specified address
* ERC20 support
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyUnlocked(_value) public returns (bool) {
bytes memory empty;
return _transfer(_to, _value, empty);
}
/**
* @dev Transfer token for a specified address
* ERC223 support
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The additional data.
*/
function transfer(address _to, uint256 _value, bytes _data) onlyUnlocked(_value) public returns (bool) {
return _transfer(_to, _value, _data);
}
/**
* @dev Transfer token for a specified address
* ERC223 support
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The additional data.
*/
function _transfer(address _to, uint256 _value, bytes _data) internal returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(_value > 0);
// catch overflow loosing tokens
// require(balances[_to] + _value > balances[_to]);
// safety update balances
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// determine if the contract given
if (isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
// emit ERC20 transfer event
emit Transfer(msg.sender, _to, _value);
// emit ERC223 transfer event
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) onlyUnlockedOf(_from, _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_value > 0);
// make balances manipulations first
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
bytes memory empty;
if (isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
// emit ERC20 transfer event
emit Transfer(_from, _to, _value);
// emit ERC223 transfer event
emit Transfer(_from, _to, _value, empty);
return true;
}
}
// File: contracts/StandardBurnableLockableToken.sol
/**
* @title StandardBurnableLockableToken
*
*/
contract StandardBurnableLockableToken is StandardLockableToken, BurnableToken {
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) onlyOwner onlyUnlockedOf(_from, _value) public {
require(_value <= allowed[_from][msg.sender]);
require(_value > 0);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
bytes memory empty;
// emit ERC223 transfer event also
emit Transfer(msg.sender, address(0), _value, empty);
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) onlyOwner onlyUnlocked(_value) public {
require(_value > 0);
_burn(msg.sender, _value);
bytes memory empty;
// emit ERC223 transfer event also
emit Transfer(msg.sender, address(0), _value, empty);
}
}
contract EngageToken is StandardBurnableLockableToken, Destructible {
string public constant name = "Engage";
uint public constant decimals = 18;
string public constant symbol = "NGAGE";
constructor() public {
// set the owner
owner = msg.sender;
admin = 0x613b42D781c59237fb51c304A5b037cDDD0dC48c;
uint256 INITIAL_SUPPLY = 1000000000 * (10**decimals);
totalSupply_ = INITIAL_SUPPLY;
bytes memory empty;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY, empty);
}
}
|
Gives owner the ability to update lockup period for all wallets. Owner can pass an epoch timecode into the function to: 1. Extend lockup period, 2. Unlock all wallets by passing &39;0&39; into the function
|
function updateGlobalUnlockTime(uint256 _epoch) public onlyOwnerOrAdmin returns (bool) {
require(_epoch >= 0);
globalUnlockTime = _epoch;
emit UpdateGlobalUnlockTime(_epoch);
}
| 6,655,485
|
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
pragma solidity ^0.6.0;
import "./FlexiblePrivacyGroupManagementInterface.sol";
contract DefaultFlexiblePrivacyGroupManagementContract is FlexiblePrivacyGroupManagementInterface {
address private _owner;
bool private _canExecute;
bytes32 private _version;
bytes32[] private distributionList;
mapping(bytes32 => uint256) private distributionIndexOf;
function getVersion() external view override returns (bytes32) {
return _version;
}
function canExecute() external view override returns (bool) {
return _canExecute;
}
function lock() public override {
require(_canExecute);
require(tx.origin == _owner, "Origin not the owner.");
_canExecute = false;
}
function unlock() public override {
require(!_canExecute);
require(tx.origin == _owner, "Origin not the owner.");
_canExecute = true;
}
function addParticipants(bytes32[] memory _publicEnclaveKeys) public override returns (bool) {
require(!_canExecute);
if (_owner == address(0x0)) {
// The account creating this group is set to be the owner
_owner = tx.origin;
}
require(tx.origin == _owner, "Origin not the owner.");
bool result = addAll(_publicEnclaveKeys);
_canExecute = true;
updateVersion();
return result;
}
function removeParticipant(bytes32 _participant) public override returns (bool) {
require(_canExecute);
require(tx.origin == _owner, "Origin not the owner.");
bool result = removeInternal(_participant);
updateVersion();
return result;
}
function getParticipants() public view override returns (bytes32[] memory) {
return distributionList;
}
function canUpgrade() external override returns (bool) {
return tx.origin == _owner;
}
//internal functions
function addAll(bytes32[] memory _publicEnclaveKeys) internal returns (bool) {
bool allAdded = true;
for (uint i = 0; i < _publicEnclaveKeys.length; i++) {
if (isMember(_publicEnclaveKeys[i])) {
emit ParticipantAdded(false, _publicEnclaveKeys[i], "Account is already a Member");
allAdded = allAdded && false;
} else {
bool result = addParticipant(_publicEnclaveKeys[i]);
string memory message = result ? "Member account added successfully" : "Account is already a Member";
emit ParticipantAdded(result, _publicEnclaveKeys[i], message);
allAdded = allAdded && result;
}
}
return allAdded;
}
function isMember(bytes32 _publicEnclaveKey) internal view returns (bool) {
return distributionIndexOf[_publicEnclaveKey] != 0;
}
function addParticipant(bytes32 _publicEnclaveKey) internal returns (bool) {
if (distributionIndexOf[_publicEnclaveKey] == 0) {
distributionList.push(_publicEnclaveKey);
distributionIndexOf[_publicEnclaveKey] = distributionList.length;
return true;
}
return false;
}
function removeInternal(bytes32 _participant) internal returns (bool) {
uint256 index = distributionIndexOf[_participant];
if (index > 0 && index <= distributionList.length) {
//move last address into index being vacated (unless we are dealing with last index)
if (index != distributionList.length) {
bytes32 lastPublicKey = distributionList[distributionList.length - 1];
distributionList[index - 1] = lastPublicKey;
distributionIndexOf[lastPublicKey] = index;
}
distributionList.pop();
distributionIndexOf[_participant] = 0;
return true;
}
return false;
}
function updateVersion() internal returns (int) {
_version = keccak256(abi.encodePacked(blockhash(block.number-1), block.coinbase, distributionList));
}
event ParticipantAdded(
bool success,
bytes32 publicEnclaveKey,
string message
);
}
|
move last address into index being vacated (unless we are dealing with last index)
|
function removeInternal(bytes32 _participant) internal returns (bool) {
uint256 index = distributionIndexOf[_participant];
if (index > 0 && index <= distributionList.length) {
if (index != distributionList.length) {
bytes32 lastPublicKey = distributionList[distributionList.length - 1];
distributionList[index - 1] = lastPublicKey;
distributionIndexOf[lastPublicKey] = index;
}
distributionList.pop();
distributionIndexOf[_participant] = 0;
return true;
}
return false;
}
| 12,557,939
|
./partial_match/97/0x1a8B7C95aA9766ACad44ed667CBB6A5F4aB683B2/sources/MasterChefV2.sol
|
Add a new lp to the pool. Can only be called by the owner.
|
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExistence[_lpToken] = true;
poolInfo.push(PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accGFTPerShare : 0,
depositFeeBP : _depositFeeBP
}));
}
| 17,204,411
|
pragma solidity ^0.5.16;
import "./CCapableErc20Delegate.sol";
import "./EIP20Interface.sol";
/**
* @notice Compound's Comptroller interface to get Comp address
*/
interface IComptroller {
function getCompAddress() external view returns (address);
function claimComp(address[] calldata holders, CToken[] calldata cTokens, bool borrowers, bool suppliers) external;
}
/**
* @title Cream's CCToken's Contract
* @notice CToken which wraps Compound's Ctoken
* @author Cream
*/
contract CCTokenDelegate is CCapableErc20Delegate {
/**
* @notice The comptroller of Compound's CToken
*/
address public underlyingComptroller;
/**
* @notice Comp token address
*/
address public comp;
/**
* @notice Container for comp rewards state
* @member balance The balance of comp
* @member index The last updated index
*/
struct RewardState {
uint balance;
uint index;
}
/**
* @notice The state of Compound's CToken supply
*/
RewardState public supplyState;
/**
* @notice The index of every Compound's CToken supplier
*/
mapping(address => uint) public supplierState;
/**
* @notice The comp amount of every user
*/
mapping(address => uint) public compUserAccrued;
/**
* @notice Delegate interface to become the implementation
* @param data The encoded arguments for becoming
*/
function _becomeImplementation(bytes memory data) public {
super._becomeImplementation(data);
underlyingComptroller = address(CToken(underlying).comptroller());
comp = IComptroller(underlyingComptroller).getCompAddress();
}
/**
* @notice Manually claim comp rewards by user
* @return The amount of comp rewards user claims
*/
function claimComp(address account) public returns (uint) {
harvestComp();
updateSupplyIndex();
updateSupplierIndex(account);
uint compBalance = compUserAccrued[account];
if (compBalance > 0) {
// Transfer user comp and subtract the balance in supplyState
EIP20Interface(comp).transfer(account, compBalance);
supplyState.balance = sub_(supplyState.balance, compBalance);
// Clear user's comp accrued.
compUserAccrued[account] = 0;
return compBalance;
}
return 0;
}
/*** CToken Overrides ***/
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
harvestComp();
updateSupplyIndex();
updateSupplierIndex(src);
updateSupplierIndex(dst);
return super.transferTokens(spender, src, dst, tokens);
}
/*** Safe Token ***/
/**
* @notice Transfer the underlying to this contract
* @param from Address to transfer funds from
* @param amount Amount of underlying to transfer
* @return The actual amount that is transferred
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
uint transferredIn = super.doTransferIn(from, amount);
harvestComp();
updateSupplyIndex();
updateSupplierIndex(from);
return transferredIn;
}
/**
* @notice Transfer the underlying from this contract
* @param to Address to transfer funds to
* @param amount Amount of underlying to transfer
*/
function doTransferOut(address payable to, uint amount) internal {
harvestComp();
updateSupplyIndex();
updateSupplierIndex(to);
super.doTransferOut(to, amount);
}
/*** Internal functions ***/
function harvestComp() internal {
address[] memory holders = new address[](1);
holders[0] = address(this);
CToken[] memory cTokens = new CToken[](1);
cTokens[0] = CToken(underlying);
// CCToken contract will never borrow assets from Compound.
IComptroller(underlyingComptroller).claimComp(holders, cTokens, false, true);
}
function updateSupplyIndex() internal {
uint compAccrued = sub_(compBalance(), supplyState.balance);
uint supplyTokens = CToken(address(this)).totalSupply();
Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
// Update supplyState.
supplyState.index = index.mantissa;
supplyState.balance = compBalance();
}
function updateSupplierIndex(address supplier) internal {
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: supplierState[supplier]});
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
if (deltaIndex.mantissa > 0) {
uint supplierTokens = CToken(address(this)).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
compUserAccrued[supplier] = add_(compUserAccrued[supplier], supplierDelta);
supplierState[supplier] = supplyIndex.mantissa;
}
}
function compBalance() internal view returns (uint) {
return EIP20Interface(comp).balanceOf(address(this));
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CCapableErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CCapableErc20 is CToken, CCapableErc20Interface, CCapableDelegateInterface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/**
* @notice Absorb excess cash into reserves.
*/
function gulp() external {
uint256 cashOnChain = getCashOnChain();
uint256 cashPrior = getCashPrior();
uint excessCash = sub_(cashOnChain, cashPrior);
totalReserves = add_(totalReserves, excessCash);
internalCash = cashOnChain;
}
/*** Safe Token ***/
/**
* @notice Gets internal balance of this contract in terms of the underlying.
* It excludes balance from direct transfer.
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
return internalCash;
}
/**
* @notice Gets total balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashOnChain() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
uint transferredIn = sub_(balanceAfter, balanceBefore);
internalCash = add_(internalCash, transferredIn);
return transferredIn;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
internalCash = sub_(internalCash, amount);
}
}
pragma solidity ^0.5.16;
import "./CCapableErc20.sol";
/**
* @title Compound's CCapableErc20Delegate Contract
* @notice CTokens which wrap an EIP-20 underlying and are delegated to
* @author Compound
*/
contract CCapableErc20Delegate is CCapableErc20 {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
// Set internal cash when becoming implementation
internalCash = getCashOnChain();
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = sub_(startingAllowance, tokens);
uint srcTokensNew = sub_(accountTokens[src], tokens);
uint dstTokensNew = add_(accountTokens[dst], tokens);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance = borrowBalanceStoredInternal(account);
uint exchangeRateMantissa = exchangeRateStoredInternal();
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
return borrowBalanceStoredInternal(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return the calculated balance or 0 if error code is non-zero
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint) {
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);
uint result = div_(principalTimesIndex, borrowSnapshot.interestIndex);
return result;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return calculated exchange rate scaled by 1e18
*/
function exchangeRateStoredInternal() internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);
uint exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));
return exchangeRate;
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
uint blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior);
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint totalBorrowsNew = add_(interestAccumulated, borrowsPrior);
uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
vars.totalSupplyNew = add_(totalSupply, vars.mintTokens);
vars.accountTokensNew = add_(accountTokens[minter], vars.mintTokens);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
vars.exchangeRateMantissa = exchangeRateStoredInternal();
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens);
vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens);
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);
vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);
vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint borrowerTokensNew = sub_(accountTokens[borrower], seizeTokens);
uint liquidatorTokensNew = add_(accountTokens[liquidator], seizeTokens);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = add_(totalReserves, actualAddAmount);
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = sub_(totalReserves, reduceAmount);
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CCapableErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
function gulp() external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegationStorageExtension is CDelegationStorage {
/**
* @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20.
*/
uint256 public internalCash;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract CCapableDelegateInterface is CDelegationStorageExtension {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_FRESHNESS_CHECK,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_FRESHNESS_CHECK,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function div_ScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint numerator = mul_(expScale, scalar);
return Exp({mantissa: div_(numerator, divisor)});
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function div_ScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) {
Exp memory fraction = div_ScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint x) pure internal returns (uint) {
if (x == 0) return 0;
uint xx = x;
uint r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint r1 = x / r;
return (r < r1 ? r : r1);
}
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
|
Transfer the underlying from this contract to Address to transfer funds to amount Amount of underlying to transfer/
|
function doTransferOut(address payable to, uint amount) internal {
harvestComp();
updateSupplyIndex();
updateSupplierIndex(to);
super.doTransferOut(to, amount);
}
| 10,063,891
|
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPool.sol";
import "../interfaces/ILendingPoolAddressesProvider.sol";
import "../utils/SafeERC20.sol";
/// @title Basic compound interactions through the DSProxy
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for stable rate and 2 for variable rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
pragma solidity ^0.6.0;
import "../interfaces/GasTokenInterface.sol";
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
pragma solidity ^0.6.0;
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
pragma solidity ^0.6.0;
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsStable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
pragma solidity ^0.6.0;
/**
@title ILendingPoolAddressesProvider interface
@notice provides the interface to fetch the LendingPoolCore address
*/
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
pragma solidity ^0.6.0;
import "../interfaces/ERC20.sol";
import "./Address.sol";
import "./SafeMath.sol";
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 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));
}
function _callOptionalReturn(ERC20 token, bytes memory data) private {
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");
}
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
pragma solidity ^0.6.0;
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
pragma solidity ^0.6.0;
library Address {
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);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
}
}
}
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
import "../interfaces/DSProxyInterface.sol";
import "./SafeERC20.sol";
/// @title Pulls a specified amount of tokens from the EOA owner account to the proxy
contract PullTokensProxy {
using SafeERC20 for ERC20;
/// @notice Pulls a token from the proxyOwner -> proxy
/// @dev Proxy owner must first give approve to the proxy address
/// @param _tokenAddr Address of the ERC20 token
/// @param _amount Amount of tokens which will be transfered to the proxy
function pullTokens(address _tokenAddr, uint _amount) public {
address proxyOwner = DSProxyInterface(address(this)).owner();
ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount);
}
}
pragma solidity ^0.6.0;
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
pragma solidity ^0.6.0;
import "../auth/Auth.sol";
import "../interfaces/DSProxyInterface.sol";
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
pragma solidity ^0.6.0;
import "./AdminAuth.sol";
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmin() {
require(admin == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/ILendingPool.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/ILoanShifter.sol";
import "../interfaces/DSProxyInterface.sol";
import "../interfaces/Vat.sol";
import "../interfaces/Manager.sol";
import "../interfaces/IMCDSubscriptions.sol";
import "../interfaces/ICompoundSubscriptions.sol";
import "../auth/AdminAuth.sol";
import "../auth/ProxyPermission.sol";
import "../exchangeV3/DFSExchangeData.sol";
import "./ShifterRegistry.sol";
import "../utils/GasBurner.sol";
import "../loggers/DefisaverLogger.sol";
/// @title LoanShifterTaker Entry point for using the shifting operation
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
// encode data
bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return getUnderlyingAddr(_address);
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function logEvent(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
pragma solidity ^0.6.0;
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
pragma solidity ^0.6.0;
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
pragma solidity ^0.6.0;
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
pragma solidity ^0.6.0;
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
pragma solidity ^0.6.0;
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
pragma solidity ^0.6.0;
import "../DS/DSGuard.sol";
import "../DS/DSAuth.sol";
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address wrapper;
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
pragma solidity ^0.6.0;
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
pragma solidity ^0.6.0;
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
pragma solidity ^0.6.0;
import "./DSAuthority.sol";
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
pragma solidity ^0.6.0;
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/SafeERC20.sol";
import "../../utils/GasBurner.sol";
contract MCDCreateTaker is GasBurner {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable burnGas(20) {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../loggers/DefisaverLogger.sol";
import "../../utils/Discount.sol";
import "../../interfaces/Spotter.sol";
import "../../interfaces/Jug.sol";
import "../../interfaces/DaiJoin.sol";
import "../../interfaces/Join.sol";
import "./MCDSaverProxyHelper.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
/// @title Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable {
address managerAddr = getManagerAddr(_managerType);
address user = getOwner(Manager(managerAddr), _cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_cdpId);
drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable {
address managerAddr = getManagerAddr(_managerType);
address user = getOwner(Manager(managerAddr), _cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_cdpId);
uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId));
uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
Manager(_managerAddr).ilks(_cdpId),
Manager(_managerAddr).urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @param _managerAddr Address of the CDP Manager
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0);
Manager(_managerAddr).flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @param _managerAddr Address of the CDP Manager
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = Manager(_managerAddr).urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
if (feeAmount > _amount / 5) {
feeAmount = _amount / 5;
}
address walletAddr = _feeRecipient.getFeeAddr();
ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount);
return feeAmount;
}
return 0;
}
}
pragma solidity ^0.6.0;
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
pragma solidity ^0.6.0;
import "./PipInterface.sol";
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
pragma solidity ^0.6.0;
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
pragma solidity ^0.6.0;
import "./Vat.sol";
import "./Gem.sol";
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
pragma solidity ^0.6.0;
import "./Gem.sol";
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
pragma solidity ^0.6.0;
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "../../interfaces/Manager.sol";
import "../../interfaces/Join.sol";
import "../../interfaces/Vat.sol";
/// @title Helper methods for MCDSaverProxy
contract MCDSaverProxyHelper is DSMath {
enum ManagerType { MCD, BPROTOCOL }
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
/// @notice Based on the manager type returns the address
/// @param _managerType Type of vault manager to use
function getManagerAddr(ManagerType _managerType) public pure returns (address) {
if (_managerType == ManagerType.MCD) {
return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
} else if (_managerType == ManagerType.BPROTOCOL) {
return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed;
}
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV3.sol";
import "../utils/ZrxAllowlist.sol";
import "./DFSExchangeData.sol";
import "./DFSExchangeHelper.sol";
import "../exchange/SaverExchangeRegistry.sol";
import "../interfaces/OffchainWrapperInterface.sol";
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) {
TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw(
TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this))
);
}
if (exData.destAddr == EXCHANGE_WETH_ADDRESS) {
require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
} else {
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) {
TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw(
TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this))
);
}
if (exData.destAddr == EXCHANGE_WETH_ADDRESS) {
require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT);
} else {
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
return (false, 0);
}
if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) {
return (false, 0);
}
// send src amount
ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount);
return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
pragma solidity ^0.6.0;
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
pragma solidity ^0.6.0;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
pragma solidity ^0.6.0;
import "./DSAuth.sol";
import "./DSNote.sol";
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
pragma solidity ^0.6.0;
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
pragma solidity ^0.6.0;
abstract contract TokenInterface {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
pragma solidity ^0.6.0;
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
contract DFSExchangeHelper {
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
address walletAddr = _feeRecipient.getFeeAddr();
if (_token == KYBER_ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(walletAddr, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src;
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../exchangeV3/DFSExchangeData.sol";
abstract contract OffchainWrapperInterface is DFSExchangeData {
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) virtual public payable returns (bool success, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract IFeeRecipient {
function getFeeAddr() public view virtual returns (address);
function changeWalletAddr(address _newWallet) public virtual;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../saver/MCDSaverProxy.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable burnGas(25) {
address managerAddr = getManagerAddr(_managerType);
uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType));
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable burnGas(25) {
address managerAddr = getManagerAddr(_managerType);
uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType));
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/ERC20.sol";
import "../../DS/DSAuth.sol";
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
pragma solidity ^0.6.0;
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../interfaces/ITokenInterface.sol";
import "../../DS/DSAuth.sol";
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ProtocolInterface.sol";
import "../interfaces/ERC20.sol";
import "../interfaces/ITokenInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "./dydx/ISoloMargin.sol";
import "./SavingsLogger.sol";
import "./dsr/DSRSavingsProtocol.sol";
import "./compound/CompoundSavingsProtocol.sol";
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
function borrowCaps(address) external virtual returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (public virtually)
Sell, // sell an amount of some token (public virtually)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function ownerSetSpreadPremium(
uint256 marketId,
Decimal.D256 memory spreadPremium
) public virtual;
function getIsGlobalOperator(address operator) public virtual view returns (bool);
function getMarketTokenAddress(uint256 marketId)
public virtual
view
returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter)
public virtual;
function getAccountValues(Account.Info memory account)
public virtual
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId)
public virtual
view
returns (address);
function getMarketInterestSetter(uint256 marketId)
public virtual
view
returns (address);
function getMarketSpreadPremium(uint256 marketId)
public virtual
view
returns (Decimal.D256 memory);
function getNumMarkets() public virtual view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient)
public virtual
returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue)
public virtual;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual;
function getIsLocalOperator(address owner, address operator)
public virtual
view
returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId)
public virtual
view
returns (Types.Par memory);
function ownerSetMarginPremium(
uint256 marketId,
Decimal.D256 memory marginPremium
) public virtual;
function getMarginRatio() public virtual view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId)
public virtual
view
returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) public virtual view returns (bool);
function getRiskParams() public virtual view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
public virtual
view
returns (address[] memory, Types.Par[] memory, Types.Wei[] memory);
function renounceOwnership() public virtual;
function getMinBorrowedValue() public virtual view returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) public virtual;
function getMarketPrice(uint256 marketId) public virtual view returns (address);
function owner() public virtual view returns (address);
function isOwner() public virtual view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient)
public virtual
returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) public virtual;
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getMarketWithInfo(uint256 marketId)
public virtual
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual;
function getLiquidationSpread() public virtual view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId)
public virtual
view
returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId)
public virtual
view
returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) public virtual view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId)
public virtual
view
returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId)
public virtual
view
returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account)
public virtual
view
returns (uint8);
function getEarningsRate() public virtual view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual;
function getRiskLimits() public virtual view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId)
public virtual
view
returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual;
function ownerSetGlobalOperator(address operator, bool approved) public virtual;
function transferOwnership(address newOwner) public virtual;
function getAdjustedAccountValues(Account.Info memory account)
public virtual
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId)
public virtual
view
returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId)
public virtual
view
returns (Interest.Rate memory);
}
pragma solidity ^0.6.0;
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/Join.sol";
import "../../DS/DSMath.sol";
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../compound/helpers/Exponential.sol";
import "../../interfaces/ERC20.sol";
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
pragma solidity ^0.6.0;
import "./CarefulMath.sol";
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
}
pragma solidity ^0.6.0;
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "./ISoloMargin.sol";
import "../../interfaces/ERC20.sol";
import "../../DS/DSAuth.sol";
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelperV2.sol";
import "../../auth/AdminAuth.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44;
address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
address market,
uint256 rateMode,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../DS/DSProxy.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPoolV2.sol";
import "../interfaces/IPriceOracleGetterAave.sol";
import "../interfaces/IAaveProtocolDataProviderV2.sol";
import "../utils/SafeERC20.sol";
import "../utils/BotRegistry.sol";
contract AaveHelperV2 is DSMath {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
uint public constant STABLE_ID = 1;
uint public constant VARIABLE_ID = 2;
/// @notice Calculates the gas cost for transaction
/// @param _oracleAddress address of oracle used
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
if (_gasCost == 0) return 0;
uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
gasCost = _gasCost;
// gas cost can't go over 10% of the whole amount
if (gasCost > (_amount / 10)) {
gasCost = _amount / 10;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) internal {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) internal {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) {
return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProviderV2 {
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPoolV2 {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
**/
function withdraw(
address asset,
uint256 amount,
address to
) external;
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external;
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2);
function setPause(bool val) external;
function paused() external view returns (bool);
}
pragma solidity ^0.6.0;
/************
@title IPriceOracleGetterAave interface
@notice Interface for the Aave price oracle.*/
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
abstract contract IAaveProtocolDataProviderV2 {
struct TokenData {
string symbol;
address tokenAddress;
}
function getAllReservesTokens() external virtual view returns (TokenData[] memory);
function getAllATokens() external virtual view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external virtual
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external virtual
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external virtual
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external virtual
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/GasBurner.sol";
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
ManagerType managerType;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable burnGas(20) {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
address managerAddr = getManagerAddr(_closeData.managerType);
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
Manager(managerAddr).urns(_closeData.cdpId),
Manager(managerAddr).urns(_closeData.cdpId),
Manager(managerAddr).ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId));
}
Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/ILoanShifter.sol";
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../mcd/create/MCDCreateProxyActions.sol";
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(address(manager), _cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(address(manager), _cdpId, _joinAddr, collAmount);
// draw debt
drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
pragma solidity ^0.6.0;
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchangeV3/DFSExchangeCore.sol";
import "./MCDCreateProxyActions.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/Manager.sol";
import "../../interfaces/Join.sol";
import "../../DS/DSProxy.sol";
import "./MCDCreateTaker.sol";
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
import "./SafeERC20.sol";
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./saver/MCDSaverProxyHelper.sol";
import "../interfaces/Spotter.sol";
contract MCDLoanInfo is MCDSaverProxyHelper {
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
struct VaultInfo {
address owner;
uint256 ratio;
uint256 collateral;
uint256 debt;
bytes32 ilk;
address urn;
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) {
address urn = manager.urns(_cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint256 collateral, uint256 debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
vaultInfo = VaultInfo({
owner: manager.owns(_cdpId),
ratio: getRatio(_cdpId, ilk),
collateral: collateral,
debt: debt,
ilk: ilk,
urn: urn
});
}
function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) {
vaultInfos = new VaultInfo[](_cdps.length);
for (uint256 i = 0; i < _cdps.length; i++) {
vaultInfos[i] = getVaultInfo(_cdps[i]);
}
}
function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) {
ratios = new uint256[](_cdps.length);
for (uint256 i = 0; i<_cdps.length; i++) {
bytes32 ilk = manager.ilks(_cdps[i]);
ratios[i] = getRatio(_cdps[i], ilk);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/Manager.sol";
import "./StaticV2.sol";
import "../saver/MCDSaverProxy.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Spotter.sol";
import "../../auth/AdminAuth.sol";
/// @title Handles subscriptions for automatic monitoring
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
pragma solidity ^0.6.0;
/// @title Implements enum Method
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
pragma solidity ^0.6.0;
import "../../interfaces/Join.sol";
import "../../interfaces/ERC20.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Flipper.sol";
import "../../interfaces/Gem.sol";
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
if(Join(_joinAddr).dec() != 18) {
amount = amount / (10**(18 - Join(_joinAddr).dec()));
}
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
pragma solidity ^0.6.0;
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/Manager.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Spotter.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "./ISubscriptionsV2.sol";
import "./StaticV2.sol";
import "./MCDMonitorProxyV2.sol";
/// @title Implements logic that allows bots to call Boost and Repay
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1000000;
uint public BOOST_GAS_COST = 1000000;
bytes4 public REPAY_SELECTOR = 0xf360ce20;
bytes4 public BOOST_SELECTOR = 0x8ec2ae25;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./StaticV2.sol";
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Implements logic for calling MCDSaverProxy always from same contract
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
uint public MIN_CHANGE_PERIOD = 6 * 1 hours;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 hours;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyOwner {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyOwner {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyOwner {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyOwner {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyOwner {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
function setChangePeriod(uint _periodInHours) public onlyOwner {
require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD);
CHANGE_PERIOD = _periodInHours * 1 hours;
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CEtherInterface.sol";
import "../../interfaces/CompoundOracleInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../utils/Discount.sol";
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "../../compound/helpers/Exponential.sol";
import "../../utils/BotRegistry.sol";
import "../../utils/SafeERC20.sol";
/// @title Utlity functions for cream contracts
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
pragma solidity ^0.6.0;
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
pragma solidity ^0.6.0;
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../exchange/SaverExchangeCore.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/Discount.sol";
import "../helpers/CreamSaverHelper.sol";
import "../../loggers/DefisaverLogger.sol";
/// @title Implements the actual logic of Repay/Boost with FL
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV2.sol";
import "../utils/ZrxAllowlist.sol";
import "./SaverExchangeHelper.sol";
import "./SaverExchangeRegistry.sol";
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
import "../utils/Discount.sol";
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/Discount.sol";
import "../helpers/CompoundSaverHelper.sol";
import "../../loggers/DefisaverLogger.sol";
/// @title Implements the actual logic of Repay/Boost with FL
contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CEtherInterface.sol";
import "../../interfaces/CompoundOracleInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../utils/Discount.sol";
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "./Exponential.sol";
import "../../utils/BotRegistry.sol";
import "../../utils/SafeERC20.sol";
/// @title Utlity functions for Compound contracts
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
}
pragma solidity ^0.6.0;
import "../../compound/helpers/CompoundSaverHelper.sol";
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../helpers/CompoundSaverHelper.sol";
/// @title Contract that implements repay/boost functionality
contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
_exData.srcAmount = borrowAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "../utils/FlashLoanReceiverBase.sol";
import "../interfaces/DSProxyInterface.sol";
import "../exchangeV3/DFSExchangeCore.sol";
import "./ShifterRegistry.sol";
import "./LoanShifterTaker.sol";
/// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy
contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth {
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
ShifterRegistry public constant shifterRegistry =
ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData) =
packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendTokenToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxyInterface(paramData.proxy).owner();
if (paramData.swapType == 1) {
// COLL_SWAP
(, uint256 amount) = _sell(exchangeData);
sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) {
// DEBT_SWAP
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendTokenToProxy(
payable(paramData.proxy),
exchangeData.srcAddr,
ERC20(exchangeData.srcAddr).balanceOf(address(this))
);
} else {
// NO_SWAP just send tokens to proxy
sendTokenAndEthToProxy(
payable(paramData.proxy),
exchangeData.srcAddr,
getBalance(exchangeData.srcAddr)
);
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(
uint256 _amount,
uint256 _fee,
bytes memory _params
)
internal
pure
returns (ParamData memory paramData, ExchangeData memory exchangeData)
{
LoanShifterTaker.LoanShiftData memory shiftData;
address proxy;
(shiftData, exchangeData, proxy) = abi.decode(
_params,
(LoanShifterTaker.LoanShiftData, ExchangeData, address)
);
bytes memory proxyData1;
bytes memory proxyData2;
uint256 openDebtAmount = (_amount + _fee);
if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) {
// MAKER FROM
proxyData1 = abi.encodeWithSignature(
"close(uint256,address,uint256,uint256)",
shiftData.id1,
shiftData.addrLoan1,
_amount,
shiftData.collAmount
);
} else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) {
// COMPOUND FROM
if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) {
// DEBT_SWAP
proxyData1 = abi.encodeWithSignature(
"changeDebt(address,address,uint256,uint256)",
shiftData.debtAddr1,
shiftData.debtAddr2,
_amount,
exchangeData.srcAmount
);
} else {
proxyData1 = abi.encodeWithSignature(
"close(address,address,uint256,uint256)",
shiftData.addrLoan1,
shiftData.debtAddr1,
shiftData.collAmount,
shiftData.debtAmount
);
}
}
if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) {
// MAKER TO
proxyData2 = abi.encodeWithSignature(
"open(uint256,address,uint256)",
shiftData.id2,
shiftData.addrLoan2,
openDebtAmount
);
} else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) {
// COMPOUND TO
if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) {
// DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2);
} else {
proxyData2 = abi.encodeWithSignature(
"open(address,address,uint256)",
shiftData.addrLoan2,
shiftData.debtAddr2,
openDebtAmount
);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: shiftData.debtAddr1,
protocol1: uint8(shiftData.fromProtocol),
protocol2: uint8(shiftData.toProtocol),
swapType: uint8(shiftData.swapType)
});
}
function sendTokenAndEthToProxy(
address payable _proxy,
address _reserve,
uint256 _amount
) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function sendTokenToProxy(
address payable _proxy,
address _reserve,
uint256 _amount
) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
} else {
_proxy.transfer(address(this).balance);
}
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../DS/DSProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../shifter/ShifterRegistry.sol";
import "./CompoundCreateTaker.sol";
/// @title Contract that receives the FL from Aave for Creating loans
contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner();
_sell(exchangeData);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
CompoundCreateTaker.CreateInfo memory createData;
address proxy;
(createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee));
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: createData.cCollAddress,
cDebtAddr: createData.cBorrowAddress
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/ILendingPool.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/SafeERC20.sol";
/// @title Opens compound positions with a leverage
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
DFSExchangeData.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/ProxyPermission.sol";
import "../utils/DydxFlashLoanBase.sol";
import "../loggers/DefisaverLogger.sol";
import "../interfaces/ERC20.sol";
/// @title Takes flash loan
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../utils/SafeMath.sol";
import "../savings/dydx/ISoloMargin.sol";
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../AaveHelperV2.sol";
import "../../../utils/GasBurner.sol";
import "../../../auth/AdminAuth.sol";
import "../../../auth/ProxyPermission.sol";
import "../../../utils/DydxFlashLoanBase.sol";
import "../../../loggers/DefisaverLogger.sol";
import "../../../interfaces/ProxyRegistryInterface.sol";
import "../../../interfaces/TokenInterface.sol";
import "../../../interfaces/ERC20.sol";
import "../../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 {
address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2;
// leaving _flAmount to be the same as the older version
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
// send msg.value for exchange to the receiver
AAVE_RECEIVER.transfer(msg.value);
address[] memory assets = new address[](1);
assets[0] = _data.srcAddr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _data.srcAmount;
// for repay we are using regular flash loan with paying back the flash loan + premium
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// create data
bytes memory encodedData = packExchangeData(_data);
bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this));
// give permission to receiver and execute tx
givePermission(AAVE_RECEIVER);
ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE);
removePermission(AAVE_RECEIVER);
}
// leaving _flAmount to be the same as the older version
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
// send msg.value for exchange to the receiver
AAVE_RECEIVER.transfer(msg.value);
address[] memory assets = new address[](1);
assets[0] = _data.srcAddr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _data.srcAmount;
uint256[] memory modes = new uint256[](1);
modes[0] = _rateMode;
// create data
bytes memory encodedData = packExchangeData(_data);
bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this));
// give permission to receiver and execute tx
givePermission(AAVE_RECEIVER);
ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
import "./DSProxyInterface.sol";
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
pragma solidity ^0.6.0;
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../interfaces/OasisInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
pragma solidity ^0.6.0;
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/OasisInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/UniswapExchangeInterface.sol";
import "../../interfaces/UniswapFactoryInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
pragma solidity ^0.6.0;
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
pragma solidity ^0.6.0;
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
walletAddr
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../interfaces/UniswapRouterInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
/// @title DFS exchange wrapper for UniswapV2
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
pragma solidity ^0.6.0;
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/UniswapRouterInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
/// @title DFS exchange wrapper for UniswapV2
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV3.sol";
import "../utils/SafeERC20.sol";
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
walletAddr
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/GasTokenInterface.sol";
import "../interfaces/IFeeRecipient.sol";
import "./SaverExchangeCore.sol";
import "../DS/DSMath.sol";
import "../loggers/DefisaverLogger.sol";
import "../auth/AdminAuth.sol";
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
address walletAddr = _feeRecipient.getFeeAddr();
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(walletAddr, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../exchange/SaverExchangeCore.sol";
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract that receives the FL from Aave for Repays/Boost
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
ManagerType managerType;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay,
uint8 managerType
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr,
managerType: ManagerType(managerType)
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address managerAddr = getManagerAddr(_saverData.managerType);
address user = getOwner(Manager(managerAddr), _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId));
uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address managerAddr = getManagerAddr(_saverData.managerType);
address user = getOwner(Manager(managerAddr), _saverData.cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../auth/AdminAuth.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../mcd/saver/MCDSaverProxyHelper.sol";
import "./MCDCloseTaker.sol";
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
address managerAddr = getManagerAddr(closeDataSent.managerType);
closeCDP(closeData, exchangeData, user, managerAddr);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user,
address _managerAddr
) internal {
paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee);
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0);
Manager(_managerAddr).flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = Manager(_managerAddr).urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == EXCHANGE_WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/SafeERC20.sol";
/// @title Receives FL from Aave and imports the position to DSProxy
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
pragma solidity ^0.6.0;
import "../../utils/GasBurner.sol";
import "../../auth/ProxyPermission.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../helpers/CreamSaverHelper.sol";
/// @title Imports cream position from the account to DSProxy
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
pragma solidity ^0.6.0;
import "../../utils/GasBurner.sol";
import "../../auth/ProxyPermission.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../helpers/CompoundSaverHelper.sol";
/// @title Imports Compound position from the account to DSProxy
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve DSProxy to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this));
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
}
pragma solidity ^0.6.0;
import "../../auth/AdminAuth.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/SafeERC20.sol";
/// @title Receives FL from Aave and imports the position to DSProxy
contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
(address cCollAddr, address cBorrowAddr, address proxy) =
abi.decode(_params, (address, address, address));
address user = DSProxyInterface(proxy).owner();
uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user);
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowAddr, _amount);
// repay compound debt on behalf of the user
require(
CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0,
"Repay borrow behalf fail"
);
bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance);
DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData);
// borrow debt now on ds proxy
bytes memory borrowProxyCallData =
formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData);
// repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call to pull tokens to DSProxy
/// @param _cTokenAddr CToken address of the collateral
/// @param _amount Amount of cTokens to pull
function formatDSProxyPullTokensCall(
address _cTokenAddr,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodeWithSignature(
"pullTokens(address,uint256)",
_cTokenAddr,
_amount
);
}
/// @notice Formats function data call borrow through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
function formatDSProxyBorrowCall(
address _cCollToken,
address _cBorrowToken,
address _borrowToken,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken,
_cBorrowToken,
_borrowToken,
_amount
);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable {
_flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount);
}
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable {
_flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = _flAmount;
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve DSProxy to pull _aCollateralToken
/// @param _market Market in which we want to import
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve DSProxy to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../utils/SafeERC20.sol";
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/CompoundOracleInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "../interfaces/CTokenInterface.sol";
import "../compound/helpers/Exponential.sol";
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../helpers/Exponential.sol";
import "../../utils/SafeERC20.sol";
import "../../utils/GasBurner.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(
0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B
);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(
address _user,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow
) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(
address _user,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow
) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) {
uint256 compBalance = 0;
for (uint256 i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance = add_(comp.compAccrued(_user), compBalance);
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getClaimableAssets(address[] memory _cTokens, address _user)
public
view
returns (bool[] memory supplyClaims, bool[] memory borrowClaims)
{
supplyClaims = new bool[](_cTokens.length);
borrowClaims = new bool[](_cTokens.length);
for (uint256 i = 0; i < _cTokens.length; ++i) {
supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0;
borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0;
}
}
function getSuppyBalance(address _cToken, address _supplier)
public
view
returns (uint256 supplierAccrued)
{
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({
mantissa: comp.compSupplierIndex(_cToken, _supplier)
});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint256 supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = supplierDelta;
}
function getBorrowBalance(address _cToken, address _borrower)
public
view
returns (uint256 borrowerAccrued)
{
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({
mantissa: comp.compBorrowerIndex(_cToken, _borrower)
});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerAmount = div_(
CTokenInterface(_cToken).borrowBalanceStored(_borrower),
marketBorrowIndex
);
uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = borrowerDelta;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CompBalance.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../CompoundBasicProxy.sol";
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.user = msg.sender;
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/CEtherInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
/// @title Basic compound interactions through the DSProxy
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/CEtherInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
/// @title Basic cream interactions through the DSProxy
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/CompoundOracleInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "../interfaces/CTokenInterface.sol";
import "./helpers/Exponential.sol";
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CompoundSafetyRatio.sol";
import "./helpers/CompoundSaverHelper.sol";
/// @title Gets data about Compound positions
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
uint borrowCap;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]),
borrowCap: comp.borrowCaps(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/BotRegistry.sol";
import "../../utils/GasBurner.sol";
import "./CompoundMonitorProxy.sol";
import "./CompoundSubscriptions.sol";
import "../../interfaces/GasTokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../CompoundSafetyRatio.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1500000;
uint public BOOST_GAS_COST = 1000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin {
compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Compound automatization
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/GasTokenInterface.sol";
import "./DFSExchangeCore.sol";
import "../DS/DSMath.sol";
import "../loggers/DefisaverLogger.sol";
import "../auth/AdminAuth.sol";
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
exData.user = _user;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
exData.user = _user;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "./DFSExchange.sol";
import "../utils/SafeERC20.sol";
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587);
function callSell(DFSExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
dfsExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
dfsExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
dfsExchange = DFSExchange(_newExchange);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CreamSafetyRatio.sol";
import "./helpers/CreamSaverHelper.sol";
/// @title Gets data about cream positions
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/ERC20.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../utils/SafeERC20.sol";
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Contract that receives the FL from Aave for Repays/Boost
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(FlashLoanReceiverBase) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchange/SaverExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../helpers/CreamSaverHelper.sol";
/// @title Contract that implements repay/boost functionality
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
import "./CreamSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
/// @title Entry point for the FL Repay Boosts, called by DSProxy
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelper.sol";
import "../../auth/AdminAuth.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../DS/DSProxy.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPool.sol";
import "../interfaces/ILendingPoolAddressesProvider.sol";
import "../interfaces/IPriceOracleGetterAave.sol";
import "../utils/SafeERC20.sol";
import "../utils/BotRegistry.sol";
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
if (_gasCost == 0) return 0;
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../AaveHelper.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/ILendingPool.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
_data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_data.user = user;
// swap
(, destAmount) = _sell(_data);
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_data.user = user;
// swap
(, destAmount) = _sell(_data);
destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount = _data.srcAmount;
destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr);
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../AaveHelperV2.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/TokenInterface.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address payable user = payable(getUserAddress());
ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this));
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
// swap
(, destAmount) = _sell(_data);
}
// take gas cost at the end
destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr);
// payback
if (_data.destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit.value(destAmount)();
}
approveToken(_data.destAddr, lendingPool);
// if destAmount higher than borrow repay whole debt
uint borrow;
if (_rateMode == STABLE_ID) {
(,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this));
} else {
(,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this));
}
ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this)));
// first return 0x fee to tx.origin as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address payable user = payable(getUserAddress());
// borrow amount
ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this));
// take gas cost at the beginning
_data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
(, destAmount) = _sell(_data);
} else {
destAmount = _data.srcAmount;
}
if (_data.destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit.value(destAmount)();
}
approveToken(_data.destAddr, lendingPool);
ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE);
(,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this));
if (!collateralEnabled) {
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../utils/SafeERC20.sol";
import "../../../interfaces/TokenInterface.sol";
import "../../../DS/DSProxy.sol";
import "../../AaveHelperV2.sol";
import "../../../auth/AdminAuth.sol";
import "../../../exchangeV3/DFSExchangeCore.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal {
(, uint swappedAmount) = _sell(_exchangeData);
address user = DSAuth(_proxy).owner();
swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr);
// if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens
uint256 msgValue = 0;
address token = _exchangeData.destAddr;
// sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
msgValue = swappedAmount;
token = ETH_ADDR;
} else {
ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount);
}
// deposit collateral on behalf of user
DSProxy(payable(_proxy)).execute{value: msgValue}(
AAVE_BASIC_PROXY,
abi.encodeWithSignature(
"deposit(address,address,uint256)",
_market,
token,
swappedAmount
)
);
}
function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal {
// we will withdraw exactly the srcAmount, as fee we keep before selling
uint valueToWithdraw = _exchangeData.srcAmount;
// take out the fee wee need to pay and sell the rest
_exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee;
(, uint swappedAmount) = _sell(_exchangeData);
// set protocol fee left to eth balance of this address
// but if destAddr is eth or weth, this also includes that value so we need to substract it
uint protocolFeeLeft = address(this).balance;
address user = DSAuth(_proxy).owner();
swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr);
// if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens
uint256 msgValue = 0;
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
protocolFeeLeft -= swappedAmount;
msgValue = swappedAmount;
} else {
ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount);
}
// first payback the loan with swapped amount
DSProxy(payable(_proxy)).execute{value: msgValue}(
AAVE_BASIC_PROXY,
abi.encodeWithSignature(
"payback(address,address,uint256,uint256)",
_market,
_exchangeData.destAddr,
swappedAmount,
_rateMode
)
);
// if some tokens left after payback (full repay) we need to return it back to the proxy owner
require(user != address(0)); // be sure that we fetched the user correctly
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
// keep protocol fee for tx.origin, but the rest of the balance return to the user
payable(user).transfer(address(this).balance - protocolFeeLeft);
} else {
// in case its a token, just return whole value back to the user, as protocol fee is always in eth
uint amount = ERC20(_exchangeData.destAddr).balanceOf(user);
ERC20(_exchangeData.destAddr).safeTransfer(user, amount);
}
// pull the amount we flash loaned in collateral to be able to payback the debt
DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw));
}
function executeOperation(
address[] calldata,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) public returns (bool) {
(
bytes memory exchangeDataBytes,
address market,
uint256 gasCost,
uint256 rateMode,
bool isRepay,
address proxy
)
= abi.decode(params, (bytes,address,uint256,uint256,bool,address));
require(initiator == proxy, "initiator isn't proxy");
ExchangeData memory exData = unpackExchangeData(exchangeDataBytes);
exData.user = DSAuth(proxy).owner();
exData.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
// this is to avoid stack too deep
uint fee = premiums[0];
uint totalValueToReturn = exData.srcAmount + fee;
// if its repay, we are using regular flash loan and payback the premiums
if (isRepay) {
repay(exData, market, gasCost, proxy, rateMode, fee);
address token = exData.srcAddr;
if (token == ETH_ADDR || token == WETH_ADDRESS) {
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)();
token = WETH_ADDRESS;
}
ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn);
} else {
boost(exData, market, gasCost, proxy);
}
tx.origin.transfer(address(this).balance);
return true;
}
/// @dev allow contract to receive eth from sell
receive() external override payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelperV2.sol";
import "../../auth/AdminAuth.sol";
// weth->eth
// deposit eth for users proxy
// borrow users token from proxy
// repay on behalf of user
// pull user supply
// take eth amount from supply (if needed more, borrow it?)
// return eth to sender
/// @title Import Aave position from account to wallet
contract AaveImportV2 is AaveHelperV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
function callFunction(
address,
Account.Info memory,
bytes memory data
) public {
(
address market,
address collateralToken,
address borrowToken,
uint256 ethAmount,
address proxy
)
= abi.decode(data, (address,address,address,uint256,address));
address user = DSProxy(payable(proxy)).owner();
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market);
uint256 globalBorrowAmountStable = 0;
uint256 globalBorrowAmountVariable = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user);
if (borrowsStable > 0) {
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID));
globalBorrowAmountStable = borrowsStable;
}
if (borrowsVariable > 0) {
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID));
globalBorrowAmountVariable = borrowsVariable;
}
}
if (globalBorrowAmountVariable > 0) {
paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID);
}
if (globalBorrowAmountStable > 0) {
paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID);
}
(address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken);
// pull coll tokens
DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user)));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal {
// payback on behalf of user
if (_token != ETH_ADDR) {
ERC20(_token).safeApprove(_proxy, _amount);
DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf));
} else {
DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf));
}
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
}
}
}
pragma solidity ^0.6.0;
import "./AaveHelperV2.sol";
import "../interfaces/ILendingPoolV2.sol";
contract AaveSafetyRatioV2 is AaveHelperV2 {
function getSafetyRatio(address _market, address _user) public view returns(uint256) {
ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool());
(,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user);
if (totalDebtETH == 0) return uint256(0);
return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "./AaveMonitorProxyV2.sol";
import "./AaveSubscriptionsV2.sol";
import "../AaveSafetyRatioV2.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner {
using SafeERC20 for ERC20;
string public constant NAME = "AaveMonitorV2";
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint public MAX_GAS_PRICE = 400000000000; // 400 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5;
AaveMonitorProxyV2 public aaveMonitorProxy;
AaveSubscriptionsV2 public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptionsV2(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
DFSExchangeData.ExchangeData memory _exData,
address _user,
uint256 _rateMode,
uint256 _flAmount
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)",
AAVE_MARKET_ADDRESS,
_exData,
_rateMode,
gasCost,
_flAmount
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
DFSExchangeData.ExchangeData memory _exData,
address _user,
uint256 _rateMode,
uint256 _flAmount
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)",
AAVE_MARKET_ADDRESS,
_exData,
_rateMode,
gasCost,
_flAmount
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptionsV2.AaveHolder memory holder;
holder = subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin {
aaveSaverProxy = _newAaveSaverProxy;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract AaveMonitorProxyV2 is AdminAuth {
using SafeERC20 for ERC20;
string public constant NAME = "AaveMonitorProxyV2";
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 hours;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Owner is able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyOwner {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Owner is able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyOwner {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point owner is able to cancel monitor change
function cancelMonitorChange() public onlyOwner {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyOwner {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyOwner {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
function setChangePeriod(uint _periodInHours) public onlyOwner {
require(_periodInHours * 1 hours > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInHours * 1 hours;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Aave automatization
contract AaveSubscriptionsV2 is AdminAuth {
string public constant NAME = "AaveSubscriptionsV2";
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPoolV2.sol";
import "./AaveHelperV2.sol";
import "../utils/SafeERC20.sol";
/// @title Basic compound interactions through the DSProxy
contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 {
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
if (_tokenAddr == ETH_ADDR) {
require(msg.value == _amount);
TokenInterface(WETH_ADDRESS).deposit{value: _amount}();
_tokenAddr = WETH_ADDRESS;
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount
function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
// if weth, pull to proxy and return ETH to user
ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this));
// needs to use balance of in case that amount is -1 for whole debt
TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this)));
msg.sender.transfer(address(this).balance);
} else {
// if not eth send directly to user
ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender);
}
}
/// @notice User borrows tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for stable rate and 2 for variable
function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this));
if (_tokenAddr == WETH_ADDRESS) {
// we do this so the user gets eth instead of weth
TokenInterface(WETH_ADDRESS).withdraw(_amount);
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be paybacked
/// @param _amount Amount of tokens to be payed back
function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit{value: msg.value}();
} else {
uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender));
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this)));
if (_tokenAddr == WETH_ADDRESS) {
// Pull if we have any eth leftover
TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this)));
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be paybacked
/// @param _amount Amount of tokens to be payed back
function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit{value: msg.value}();
} else {
uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this)));
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf);
if (_tokenAddr == WETH_ADDRESS) {
// we do this so the user gets eth instead of weth
TokenInterface(WETH_ADDRESS).withdraw(_amount);
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
(,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
// stable = 1, variable = 2
function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode);
}
function changeToWeth(address _token) private view returns(address) {
if (_token == ETH_ADDR) {
return WETH_ADDRESS;
}
return _token;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./AaveSafetyRatioV2.sol";
import "../interfaces/IAaveProtocolDataProviderV2.sol";
contract AaveLoanInfoV2 is AaveSafetyRatioV2 {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowStableAmounts;
uint256[] borrowVariableAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRateVariable;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
bool borrowinEnabled;
bool stableBorrowRateEnabled;
}
struct ReserveData {
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 totalVariableDebt;
uint256 liquidityRate;
uint256 variableBorrowRate;
uint256 stableBorrowRate;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrowsStable;
uint256 borrowsVariable;
uint256 stableBorrowRate;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _user Address of the user
function getRatio(address _market, address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_market, _user);
}
/// @notice Fetches Aave prices for tokens
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens);
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]);
}
}
function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_market, _users[i]);
}
}
/// @notice Information about reserves
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]);
(address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: aToken,
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) {
(
, // uint256 decimals
uint256 ltv,
uint256 liquidationThreshold,
, // uint256 liquidationBonus
, // uint256 reserveFactor
bool usageAsCollateralEnabled,
bool borrowinEnabled,
bool stableBorrowRateEnabled,
, // bool isActive
// bool isFrozen
) = _dataProvider.getReserveConfigurationData(_token);
ReserveData memory t;
(
t.availableLiquidity,
t.totalStableDebt,
t.totalVariableDebt,
t.liquidityRate,
t.variableBorrowRate,
t.stableBorrowRate,
,
,
,
) = _dataProvider.getReserveData(_token);
(address aToken,,) = _dataProvider.getReserveTokensAddresses(_token);
uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token);
_tokenInfo = TokenInfoFull({
aTokenAddress: aToken,
underlyingTokenAddress: _token,
supplyRate: t.liquidityRate,
borrowRateVariable: t.variableBorrowRate,
borrowRateStable: t.stableBorrowRate,
totalSupply: ERC20(aToken).totalSupply(),
availableLiquidity: t.availableLiquidity,
totalBorrow: t.totalVariableDebt+t.totalStableDebt,
collateralFactor: ltv,
liquidationRatio: liquidationThreshold,
price: price,
usageAsCollateralEnabled: usageAsCollateralEnabled,
borrowinEnabled: borrowinEnabled,
stableBorrowRateEnabled: stableBorrowRateEnabled
});
}
/// @notice Information about reserves
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _market, address _user) public view returns (LoanData memory data) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowStableAmounts: new uint[](reserves.length),
borrowVariableAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowStablePos = 0;
uint64 borrowVariablePos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i].tokenAddress;
(uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowsStable > 0) {
uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowStablePos] = reserve;
data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth;
borrowStablePos++;
}
// Sum up debt in Eth
if (borrowsVariable > 0) {
uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowVariablePos] = reserve;
data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth;
borrowVariablePos++;
}
}
data.ratio = uint128(getSafetyRatio(_market, _user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_market, _users[i]);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelper.sol";
import "../../auth/AdminAuth.sol";
// weth->eth
// deposit eth for users proxy
// borrow users token from proxy
// repay on behalf of user
// pull user supply
// take eth amount from supply (if needed more, borrow it?)
// return eth to sender
/// @title Import Aave position from account to wallet
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
function callFunction(
address,
Account.Info memory,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address proxy
)
= abi.decode(data, (address,address,uint256,address));
address user = DSProxy(payable(proxy)).owner();
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull coll tokens
DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user)));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
}
}
}
pragma solidity ^0.6.0;
import "./AaveHelper.sol";
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "./AaveMonitorProxy.sol";
import "./AaveSubscriptions.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../AaveSafetyRatio.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint public MAX_GAS_PRICE = 400000000000; // 400 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin {
aaveSaverProxy = _newAaveSaverProxy;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Aave automatization
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./AaveSafetyRatio.sol";
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
uint256 borrowRate;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV2.sol";
import "./SaverExchangeHelper.sol";
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "./SaverExchange.sol";
import "../utils/SafeERC20.sol";
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../DFSExchangeHelper.sol";
import "../../interfaces/OffchainWrapperInterface.sol";
import "../../interfaces/TokenInterface.sol";
contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath {
string public constant ERR_SRC_AMOUNT = "Not enough funds";
string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee";
string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0";
using SafeERC20 for ERC20;
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _type Action type (buy or sell)
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) override public payable returns (bool success, uint256) {
// check that contract have enough balance for exchange and protocol fee
require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT);
require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE);
/// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell
/// @dev safeApprove is modified to always first set approval to 0, then to exact amount
if (_type == ActionType.SELL) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
} else {
uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount);
}
// we know that it will be eth if dest addr is either weth or eth
address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr;
uint256 tokensBefore = getBalance(destAddr);
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
uint256 tokensSwaped = 0;
if (success) {
// get the current balance of the swaped tokens
tokensSwaped = getBalance(destAddr) - tokensBefore;
require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO);
}
// returns all funds from src addr, dest addr and eth funds (protocol fee leftovers)
sendLeftover(_exData.srcAddr, destAddr, msg.sender);
return (success, tokensSwaped);
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../DFSExchangeHelper.sol";
import "../../interfaces/OffchainWrapperInterface.sol";
import "../../interfaces/TokenInterface.sol";
contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath {
string public constant ERR_SRC_AMOUNT = "Not enough funds";
string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee";
string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0";
using SafeERC20 for ERC20;
/// @notice Takes order from Scp and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _type Action type (buy or sell)
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) override public payable returns (bool success, uint256) {
// check that contract have enough balance for exchange and protocol fee
require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT);
require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE);
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up
writeUint256(_exData.offchainData.callData, 36, srcAmount);
}
// we know that it will be eth if dest addr is either weth or eth
address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr;
uint256 tokensBefore = getBalance(destAddr);
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
uint256 tokensSwaped = 0;
if (success) {
// get the current balance of the swaped tokens
tokensSwaped = getBalance(destAddr) - tokensBefore;
require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO);
}
// returns all funds from src addr, dest addr and eth funds (protocol fee leftovers)
sendLeftover(_exData.srcAddr, destAddr, msg.sender);
return (success, tokensSwaped);
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
import "./CompoundSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
/// @title Entry point for the FL Repay Boosts, called by DSProxy
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/ICompoundSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/IAaveSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract AaveSubscriptionsProxyV2 is ProxyPermission {
string public constant NAME = "AaveSubscriptionsProxyV2";
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD;
address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/IAaveSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
import "../../DS/DSGuard.sol";
import "../../DS/DSAuth.sol";
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/OsmMom.sol";
import "../../interfaces/Osm.sol";
import "../../auth/AdminAuth.sol";
import "../../interfaces/Manager.sol";
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
pragma solidity ^0.6.0;
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
pragma solidity ^0.6.0;
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
pragma solidity ^0.6.0;
import "./DSProxy.sol";
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
//TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
|
Buys a _destAmount of tokens at Kyber _srcAddr From token _destAddr To token _destAmount To amount return uint srcAmount
|
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
srcAmountAfter = address(this).balance;
}
return (srcAmount - srcAmountAfter);
}
| 380,859
|
./partial_match/1/0x3355fE877a869Dd98454B4C4a5dDE24C881a4E26/sources/JETTON.sol
|
Maximum tx size and wallet size exclude from paying fees or having max transaction amount
|
constructor() ERC20("JetTon Games", "JETTON") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 10;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 30;
uint256 totalSupply = 100_000_000 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100;
maxWallet = totalSupply * 1 / 100;
swapTokensAtAmount = totalSupply * 1 / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,751,013
|
./full_match/1/0x37ff4bc9a425F37d3Af95662c9D88A88d05f3417/sources/browser/TokensTypeStorage.sol
|
allow add new token type from trade portals Don't flag this token if this token alredy registred convert string to bytes32 flag new token Add new type
|
function addNewTokenType(address _token, string calldata _type) external onlyPermitted {
if(isRegistred[_token])
return;
bytes32 typeToBytes = stringToBytes32(_type);
getType[_token] = typeToBytes;
isRegistred[_token] = true;
if(!isTypeRegistred[typeToBytes]){
isTypeRegistred[typeToBytes] = true;
allTypes.push(typeToBytes);
}
}
| 4,951,271
|
pragma solidity ^0.6.12;
/**
* @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;
}
}
/**
* @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);
}
interface ICoTraderGlobalConfig {
function MAX_TOKENS() external view returns(uint256);
function TRADE_FREEZE_TIME() external view returns(uint256);
function DW_FREEZE_TIME() external view returns(uint256);
function PLATFORM_ADDRESS() external view returns(address);
}
interface IFundValueOracle {
function requestValue(address _fundAddress, uint256 _fee) external payable returns (bytes32 requestId);
function getFundValueByID(bytes32 _requestId) external view returns(uint256 value);
function fee() external returns(uint256);
}
interface PermittedAddressesInterface {
function permittedAddresses(address _address) external view returns(bool);
function addressesTypes(address _address) external view returns(string memory);
function isMatchTypes(address _address, uint256 addressType) external view returns(bool);
}
interface DefiPortalInterface {
function callPayableProtocol(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes calldata _additionalData,
bytes32[] calldata _additionalArgs
)
external
payable
returns(
string memory eventType,
address[] memory tokensToReceive,
uint256[] memory amountsToReceive
);
function callNonPayableProtocol(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes calldata _additionalData,
bytes32[] calldata _additionalArgs
)
external
returns(
string memory eventType,
address[] memory tokensToReceive,
uint256[] memory amountsToReceive
);
}
interface PoolPortalInterface {
function buyPool
(
uint256 _amount,
uint _type,
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] calldata _connectorsAmount,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
external
payable
returns(uint256 poolAmountReceive, uint256[] memory connectorsSpended);
function sellPool
(
uint256 _amount,
uint _type,
IERC20 _poolToken,
bytes32[] calldata _additionalArgs,
bytes calldata _additionData
)
external
payable
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
);
}
// interface for fund contract
interface IExchangePortal {
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
bool _verifyDestanation
)
external
payable
returns (uint256);
}
/*
The SmartFund contract is what holds all the tokens and ether, and contains all the logic
for calculating its value (and ergo profit), allows users to deposit/withdraw their funds,
and calculates the fund managers cut of the funds profit among other things.
The SmartFund gets the value of its token holdings (in Ether) and trades through the ExchangePortal
contract. This means that as new exchange capabalities are added to new exchange portals, the
SmartFund will be able to upgrade to a new exchange portal, and trade a wider variety of assets
with a wider variety of exchanges. The SmartFund is also connected to a permittedAddresses contract,
which determines which exchange, pool, defi portals the SmartFund is allowed to connect to, restricting
the fund owners ability to connect to a potentially malicious contract.
In additional this contract can use pools and defi protocols voa pool and defi portals.
*/
/*
* @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 { }
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;
}
}
/**
* @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;
}
}
/**
* @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");
}
}
/**
* @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");
}
}
}
abstract contract SmartFundCore is Ownable, IERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Fund type
bool public isLightFund = false;
// Total amount of ether or stable deposited by all users
uint256 public totalWeiDeposited;
// Total amount of ether or stable withdrawn by all users
uint256 public totalWeiWithdrawn;
// The Interface of the Exchange Portal
IExchangePortal public exchangePortal;
// The Interface of pool portall
PoolPortalInterface public poolPortal;
// The interface of DefiPortal
DefiPortalInterface public defiPortal;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedAddressesInterface public permittedAddresses;
// portals recognizes ETH by this address
IERC20 constant internal ETH_TOKEN_ADDRESS = IERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
// For ERC20 compliance
string public name;
// Percentages are rounded to 3 decimal places
uint256 public TOTAL_PERCENTAGE = 10000;
// The percentage of earnings paid to the fund manager. 10000 = 100%
// e.g. 10% is 1000
uint256 public successFee;
// The percentage of fund manager earnings paid to the platform. 10000 = 100%
// e.g. 10% is 1000
uint256 public platformFee;
// An array of all the erc20 token addresses the smart fund holds
address[] public tokenAddresses;
// Boolean value that determines whether the fund accepts deposits from anyone or
// only specific addresses approved by the manager
bool public onlyWhitelist;
// Mapping of addresses that are approved to deposit if the manager only want's specific
// addresses to be able to invest in their fund
mapping (address => bool) public whitelist;
uint public version = 8;
// the total number of shares in the fund
uint256 public totalShares;
// Denomination of initial shares
uint256 constant internal INITIAL_SHARES = 10 ** 18;
// The earnings the fund manager has already cashed out
uint256 public fundManagerCashedOut;
// for ETH and USD fund this asset different
address public coreFundAsset;
// If true the contract will require each new asset to buy to be on a special Merkle tree list
bool public isRequireTradeVerification;
// Oracle contract instance
IFundValueOracle public fundValueOracle;
// Data for Oracle updates
bytes32 public latestOracleRequestID;
uint256 public latestOracleCallOnTime;
uint256 public latestOracleCallOnBlock;
address public latestOracleCaller;
// CoTrader platform config
ICoTraderGlobalConfig public cotraderGlobalConfig;
// how many shares belong to each address
mapping (address => uint256) public addressToShares;
// so that we can easily check that we don't add duplicates to our array
mapping (address => bool) public tokensTraded;
// this is really only being used to more easily show profits, but may not be necessary
// if we do a lot of this offchain using events to track everything
// total `depositToken` deposited - total `depositToken` withdrawn
mapping (address => int256) public addressesNetDeposit;
// Events
event DefiCall(
string eventType,
address[] tokensToSend,
uint256[] amountsToSend,
address[] tokensToReceive,
uint256[] amountsToReceive
);
event BuyPool(
address poolAddress,
uint256 poolAmount,
address[] connectorsAddress,
uint256[] connectorsAmount);
event SellPool(
address poolAddress,
uint256 poolAmount,
address[] connectorsAddress,
uint256[] connectorsAmount);
event Deposit(address indexed user, uint256 amount, uint256 sharesReceived, uint256 totalShares);
event Withdraw(address indexed user, uint256 sharesRemoved, uint256 totalShares);
event Trade(address src, uint256 srcAmount, address dest, uint256 destReceived);
event SmartFundCreated(address indexed owner);
event OracleUpdate(address caller, uint256 triggerTime, bytes32 id);
constructor(
address _owner,
string memory _name,
uint256 _successFee,
address _exchangePortalAddress,
address _poolPortalAddress,
address _defiPortal,
address _permittedAddresses,
address _coreFundAsset,
address _fundValueOracle,
bool _isRequireTradeVerification,
address _cotraderGlobalConfig
)public{
// never allow a 100% fee
require(_successFee < TOTAL_PERCENTAGE);
name = _name;
successFee = _successFee;
platformFee = _successFee; // platform fee the same as manager fee
// Init manager
if(_owner == address(0)){
transferOwnership(msg.sender);
}
else{
transferOwnership(_owner);
}
// Initial Token is Ether
tokenAddresses.push(address(ETH_TOKEN_ADDRESS));
// Initial interfaces
exchangePortal = IExchangePortal(_exchangePortalAddress);
poolPortal = PoolPortalInterface(_poolPortalAddress);
defiPortal = DefiPortalInterface(_defiPortal);
permittedAddresses = PermittedAddressesInterface(_permittedAddresses);
// Initial core assets
coreFundAsset = _coreFundAsset;
// Initial fund Oracle
fundValueOracle = IFundValueOracle(_fundValueOracle);
// Initial check if fund require trade verification or not
isRequireTradeVerification = _isRequireTradeVerification;
// Initial platform config
cotraderGlobalConfig = ICoTraderGlobalConfig(_cotraderGlobalConfig);
emit SmartFundCreated(owner());
}
// Modifiers
// We use function instead modifiers because modifiers require more bytes
// Not allow trade while user do deposit or withdraw
function verifyTradeBetweenDW() internal view {
require(
now >= latestOracleCallOnTime + cotraderGlobalConfig.TRADE_FREEZE_TIME(),
"FREEZE_FOR_UPDATE_PRICE"
);
}
// not allow call user B (for a freeze minutes) if user A not finished operation
// allow call any user for a first deposit
function verifyDWSender() internal view {
if(totalShares > 0){
if(latestOracleCallOnTime + cotraderGlobalConfig.TRADE_FREEZE_TIME() >= now){
require(msg.sender == latestOracleCaller, "NOT_LATEST_ORACLE_CALLER");
}
else{
revert("ORACLE_TIME_EXPIRED");
}
}
}
// allow update oracle price
// _oracleTokenAddress it's fee token address
function updateFundValueFromOracle(address _oracleTokenAddress, uint256 _oracleFee) public payable {
// allow call Oracle only after a certain time
require(now >= latestOracleCallOnTime + cotraderGlobalConfig.DW_FREEZE_TIME(), "DW_FREEZE");
// pay for using Oracle with ETH
if(_oracleTokenAddress == address(ETH_TOKEN_ADDRESS)){
require(msg.value == _oracleFee, "REQUIRE_ETH");
// call oracle
latestOracleRequestID = fundValueOracle.requestValue.value(_oracleFee)(address(this), _oracleFee);
}
// for using Oracle with ERC20
else{
require(msg.value == 0, "NO_NEED_ETH");
// transfer oracle token from sender and approve to oracle portal
_transferFromSenderAndApproveTo(IERC20(_oracleTokenAddress), _oracleFee, address(fundValueOracle));
// call oracle
latestOracleRequestID = fundValueOracle.requestValue(address(this), _oracleFee);
}
// update data
latestOracleCallOnTime = now;
latestOracleCallOnBlock = block.number;
latestOracleCaller = msg.sender;
// emit events
emit OracleUpdate(latestOracleCaller, latestOracleCallOnTime, latestOracleRequestID);
}
// core function for calculate deposit and withdraw and managerWithdraw
// return data from Oracle
function calculateFundValue() public view returns (uint256) {
// return latest data from Oracle
return fundValueOracle.getFundValueByID(latestOracleRequestID);
}
/**
* @dev Sends (_mul/_div) of every token (and ether) the funds holds to _withdrawAddress
*
* @param _mul The numerator
* @param _div The denominator
* @param _withdrawAddress Address to send the tokens/ether to
*
* NOTE: _withdrawAddress changed from address to address[] arrays because balance calculation should be performed
* once for all usesr who wants to withdraw from the current balance.
*
*/
function _withdraw(
uint256[] memory _mul,
uint256[] memory _div,
address[] memory _withdrawAddress
)
internal
returns (uint256)
{
for (uint8 i = 1; i < tokenAddresses.length; i++) {
// Transfer that _mul/_div of each token we hold to the user
IERC20 token = IERC20(tokenAddresses[i]);
uint256 fundAmount = token.balanceOf(address(this));
// Transfer ERC20 to _withdrawAddress
for(uint8 j = 0; j < _withdrawAddress.length; j++){
// calculate withdraw ERC20 share
uint256 payoutAmount = fundAmount.mul(_mul[j]).div(_div[j]);
if(payoutAmount > 0)
token.transfer(_withdrawAddress[j], payoutAmount);
}
}
// Transfer ETH to _withdrawAddress
uint256 etherBalance = address(this).balance;
for(uint8 k = 0; k < _withdrawAddress.length; k++){
// calculate withdraw ETH share
uint256 etherPayoutAmount = (etherBalance).mul(_mul[k]).div(_div[k]);
if(etherPayoutAmount > 0)
payable(_withdrawAddress[k]).transfer(etherPayoutAmount);
}
}
/**
* @dev Withdraws users fund holdings, sends (userShares/totalShares) of every held token
* to msg.sender, defaults to 100% of users shares.
*
* @param _percentageWithdraw The percentage of the users shares to withdraw.
*/
function withdraw(uint256 _percentageWithdraw) external {
verifyDWSender();
require(totalShares != 0, "EMPTY_SHARES");
require(_percentageWithdraw <= TOTAL_PERCENTAGE, "WRONG_PERCENT");
uint256 percentageWithdraw = (_percentageWithdraw == 0) ? TOTAL_PERCENTAGE : _percentageWithdraw;
uint256 addressShares = addressToShares[msg.sender];
uint256 numberOfWithdrawShares = addressShares.mul(percentageWithdraw).div(TOTAL_PERCENTAGE);
uint256 fundManagerCut;
uint256 fundValue;
// Withdraw the users share minus the fund manager's success fee
(fundManagerCut, fundValue, ) = calculateFundManagerCut();
// reset latest Oracle Caller for protect from double call
latestOracleCaller = address(0);
uint256 withdrawShares = numberOfWithdrawShares.mul(fundValue.sub(fundManagerCut)).div(fundValue);
// prepare call data for _withdarw
address[] memory spenders = new address[](1);
spenders[0] = msg.sender;
uint256[] memory value = new uint256[](1);
value[0] = totalShares;
uint256[] memory cut = new uint256[](1);
cut[0] = withdrawShares;
// do withdraw
_withdraw(cut, value, spenders);
// Store the value we are withdrawing in ether
uint256 valueWithdrawn = fundValue.mul(withdrawShares).div(totalShares);
totalWeiWithdrawn = totalWeiWithdrawn.add(valueWithdrawn);
addressesNetDeposit[msg.sender] -= int256(valueWithdrawn);
// Subtract from total shares the number of withdrawn shares
totalShares = totalShares.sub(numberOfWithdrawShares);
addressToShares[msg.sender] = addressToShares[msg.sender].sub(numberOfWithdrawShares);
emit Withdraw(msg.sender, numberOfWithdrawShares, totalShares);
}
/**
* @dev Facilitates a trade of the funds holdings via the exchange portal
*
* @param _source ERC20 token to convert from
* @param _sourceAmount Amount to convert (in _source token)
* @param _destination ERC20 token to convert to
* @param _type The type of exchange to trade with
* @param _proof Merkle tree proof (if not used just set [])
* @param _positions Merkle tree positions (if not used just set [])
* @param _additionalData For additional data (if not used just set "0x0")
* @param _minReturn Min expected amount of destination
*/
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
uint256 _minReturn
)
external
onlyOwner
{
verifyTradeBetweenDW();
require(_minReturn > 0, "MIN_RETURN_0");
uint256 receivedAmount;
if (_source == ETH_TOKEN_ADDRESS) {
// Make sure fund contains enough ether
require(address(this).balance >= _sourceAmount, "NOT_ENOUGH_ETH");
// Call trade on ExchangePortal along with ether
receivedAmount = exchangePortal.trade.value(_sourceAmount)(
_source,
_sourceAmount,
_destination,
_type,
_proof,
_positions,
_additionalData,
isRequireTradeVerification
);
} else {
_source.approve(address(exchangePortal), _sourceAmount);
receivedAmount = exchangePortal.trade(
_source,
_sourceAmount,
_destination,
_type,
_proof,
_positions,
_additionalData,
isRequireTradeVerification
);
}
// make sure fund recive destanation
require(receivedAmount >= _minReturn, "RECEIVED_LESS_THAN_MIN");
// add token to trader list
_addToken(address(_destination));
// emit event
emit Trade(
address(_source),
_sourceAmount,
address(_destination),
receivedAmount);
}
/**
* @dev buy pool via pool portal
*
* @param _amount For Bancor amount it's relay, for Uniswap amount it's ETH, for Bancor and Uniswap v2 can be 0
* @param _type type of pool (0 - Bancor, 1 - Uniswap)
* @param _poolToken address of relay for Bancor and exchange for Uniswap
* @param _connectorsAddress address of pool connectors
* @param _connectorsAmount amount of pool connectors
* @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty
* @param _additionData for provide any additional data, if not used just set "0x"
*/
function buyPool(
uint256 _amount,
uint _type,
address _poolToken,
address[] calldata _connectorsAddress,
uint256[] memory _connectorsAmount, // WARNING: this array rewrite from buyPool return (details below)
bytes32[] calldata _additionalArgs,
bytes calldata _additionData
)
external
onlyOwner
{
verifyTradeBetweenDW();
// for determine the exact number of received pool
uint256 poolAmountReceive;
// approve connectors
// etherAmount for detect ETH case
uint256 etherAmount = approveArrayOfTokensToSpender(
_connectorsAddress,
_connectorsAmount,
address(poolPortal)
);
// buy pool with ETH (payable case)
if(etherAmount > 0){
// WARNING: rewrire _connectorsAmount from return
// some pools can return some remains for connectors, and for get correct result,
// for connectors amount to spend for emit event
// poolPortal calculates and return exactly how many tokens were spent (total - remains),
// unfortunate due stack too deep issue, we can't declarate new variable
// so we rewrire _connectorsAmount
(poolAmountReceive, _connectorsAmount) = poolPortal.buyPool.value(etherAmount)(
_amount,
_type,
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalArgs,
_additionData
);
}
// buy pool only with ERC20 (non payable case)
else{
// WARNING: rewrire _connectorsAmount from return
(poolAmountReceive, _connectorsAmount) = poolPortal.buyPool(
_amount,
_type,
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalArgs,
_additionData
);
}
// make sure fund receive pool token
require(poolAmountReceive > 0, "EMPTY_POOL");
// Add pool as ERC20 for withdraw
_addToken(_poolToken);
// emit event
emit BuyPool(
_poolToken,
poolAmountReceive,
_connectorsAddress,
_connectorsAmount);
}
/**
* @dev sell pool via pool portal
*
* @param _amount amount of Bancor relay or Uniswap exchange to sell
* @param _type type of pool (0 - Bancor, 1 - Uniswap)
* @param _poolToken address of Bancor relay or Uniswap exchange
* @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty
* @param _additionData for provide any additional data, if not used just set "0x"
*/
function sellPool(
uint256 _amount,
uint _type,
IERC20 _poolToken,
bytes32[] calldata _additionalArgs,
bytes calldata _additionData
)
external
onlyOwner
{
verifyTradeBetweenDW();
// approve pool
_poolToken.approve(address(poolPortal), _amount);
// sell pool
(address[] memory connectorsAddress,
uint256[] memory connectorsAmount) = poolPortal.sellPool(
_amount,
_type,
_poolToken,
_additionalArgs,
_additionData
);
// Add connectors to fund
for(uint8 i = 0; i < connectorsAddress.length; i++){
_addToken(connectorsAddress[i]);
}
// event
emit SellPool(
address(_poolToken),
_amount,
connectorsAddress,
connectorsAmount);
}
/**
* @dev allow manager use newest DEFI protocols
* NOTE: all logic in DEFI portal hardcoded, and also fund manager can't update
* non permitted DEFI portal, so this is safe call
*
* @param _additionalData params data packed in bytes
* @param _additionalArgs additional params array for quick unpack
*/
function callDefiPortal(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes32[] calldata _additionalArgs,
bytes calldata _additionalData
)
external
onlyOwner
{
verifyTradeBetweenDW();
// event data
string memory eventType;
address[] memory tokensToReceive;
uint256[] memory amountsToReceive;
// approve connectors
// etherAmount for detect ETH case
uint256 etherAmount = approveArrayOfTokensToSpender(
tokensToSend,
amountsToSend,
address(defiPortal)
);
// call defi payable case
if(etherAmount > 0){
(eventType,
tokensToReceive,
amountsToReceive) = defiPortal.callPayableProtocol.value(etherAmount)(
tokensToSend,
amountsToSend,
_additionalData,
_additionalArgs
);
}
// call defi not payable case
else{
(eventType,
tokensToReceive,
amountsToReceive) = defiPortal.callNonPayableProtocol(
tokensToSend,
amountsToSend,
_additionalData,
_additionalArgs
);
}
// add new tokens in fund
for(uint8 i = 0; i < tokensToReceive.length; i++){
_addToken(tokensToReceive[i]);
}
// emit event
emit DefiCall(
eventType,
tokensToSend,
amountsToSend,
tokensToReceive,
amountsToReceive
);
}
// pivate helper for approve arary of tokens
// spender can be Pool or Defi portals
function approveArrayOfTokensToSpender(
address[] memory addresses,
uint256[] memory amounts,
address spender
)
private
returns (uint256 etherAmount)
{
for(uint8 i = 0; i < addresses.length; i++){
if(addresses[i] != address(ETH_TOKEN_ADDRESS)){
// approve
IERC20(addresses[i]).approve(spender, amounts[i]);
}
else{
etherAmount = amounts[i];
}
}
}
// return all tokens addresses from fund
function getAllTokenAddresses() external view returns (address[] memory) {
return tokenAddresses;
}
/**
* @dev Adds a token to tokensTraded if it's not already there
* @param _token The token to add
*/
function _addToken(address _token) internal {
// don't add token to if we already have it in our list
if (tokensTraded[_token] || (_token == address(ETH_TOKEN_ADDRESS)))
return;
tokensTraded[_token] = true;
tokenAddresses.push(_token);
uint256 tokenCount = tokenAddresses.length;
// we can't hold more than MAX_TOKENS tokens
require(tokenCount <= cotraderGlobalConfig.MAX_TOKENS(), "MAX_TOKENS");
}
/**
* @dev Removes a token from tokensTraded
*
* @param _token The address of the token to be removed
* @param _tokenIndex The index of the token to be removed
*
*/
function removeToken(address _token, uint256 _tokenIndex) public onlyOwner {
require(_token != address(ETH_TOKEN_ADDRESS));
require(tokensTraded[_token]);
require(IERC20(_token).balanceOf(address(this)) == 0);
require(tokenAddresses[_tokenIndex] == _token);
tokensTraded[_token] = false;
// remove token from array
uint256 arrayLength = tokenAddresses.length - 1;
tokenAddresses[_tokenIndex] = tokenAddresses[arrayLength];
delete tokenAddresses[arrayLength];
tokenAddresses.pop();
}
/**
* @dev Calculates the amount of shares received according to ether deposited
*
* @param _amount Amount of ether to convert to shares
*
* @return Amount of shares to be received
*/
function calculateDepositToShares(uint256 _amount) internal view returns (uint256) {
uint256 fundManagerCut;
uint256 fundValue;
// If there are no shares in the contract, whoever deposits owns 100% of the fund
// we will set this to 10^18 shares, but this could be any amount
if (totalShares == 0)
return INITIAL_SHARES;
(fundManagerCut, fundValue, ) = calculateFundManagerCut();
uint256 fundValueBeforeDeposit = fundValue.sub(fundManagerCut);
if (fundValueBeforeDeposit == 0)
return 0;
return _amount.mul(totalShares).div(fundValueBeforeDeposit);
}
/**
* @dev Calculates the fund managers cut, depending on the funds profit and success fee
*
* @return fundManagerRemainingCut The fund managers cut that they have left to withdraw
* @return fundValue The funds current value
* @return fundManagerTotalCut The fund managers total cut of the profits until now
*/
function calculateFundManagerCut() public view returns (
uint256 fundManagerRemainingCut, // fm's cut of the profits that has yet to be cashed out (in `depositToken`)
uint256 fundValue, // total value of fund (in `depositToken`)
uint256 fundManagerTotalCut // fm's total cut of the profits (in `depositToken`)
) {
fundValue = calculateFundValue();
// The total amount of ether currently deposited into the fund, takes into account the total ether
// withdrawn by investors as well as ether withdrawn by the fund manager
// NOTE: value can be negative if the manager performs well and investors withdraw more
// ether than they deposited
int256 curtotalWeiDeposited = int256(totalWeiDeposited) - int256(totalWeiWithdrawn.add(fundManagerCashedOut));
// If profit < 0, the fund managers totalCut and remainingCut are 0
if (int256(fundValue) <= curtotalWeiDeposited) {
fundManagerTotalCut = 0;
fundManagerRemainingCut = 0;
} else {
// calculate profit. profit = current fund value - total deposited + total withdrawn + total withdrawn by fm
uint256 profit = uint256(int256(fundValue) - curtotalWeiDeposited);
// remove the money already taken by the fund manager and take percentage
fundManagerTotalCut = profit.mul(successFee).div(TOTAL_PERCENTAGE);
fundManagerRemainingCut = fundManagerTotalCut.sub(fundManagerCashedOut);
}
}
/**
* @dev Allows the fund manager to withdraw their cut of the funds profit
*/
function fundManagerWithdraw() external onlyOwner {
verifyDWSender();
uint256 fundManagerCut;
uint256 fundValue;
(fundManagerCut, fundValue, ) = calculateFundManagerCut();
uint256 platformCut = (platformFee == 0) ? 0 : fundManagerCut.mul(platformFee).div(TOTAL_PERCENTAGE);
// prepare call data for _withdarw
address[] memory spenders = new address[](2);
spenders[0] = cotraderGlobalConfig.PLATFORM_ADDRESS();
spenders[1] = owner();
uint256[] memory value = new uint256[](2);
value[0] = fundValue;
value[1] = fundValue;
uint256[] memory cut = new uint256[](2);
cut[0] = platformCut;
cut[1] = fundManagerCut - platformCut;
// do withdraw
_withdraw(cut, value, spenders);
// add report
fundManagerCashedOut = fundManagerCashedOut.add(fundManagerCut);
}
/**
* @dev Allows the manager to set whether or not only whitelisted addresses can deposit into
* their fund
*
* @param _onlyWhitelist boolean representing whether only whitelisted addresses can deposit
*/
function setWhitelistOnly(bool _onlyWhitelist) external onlyOwner {
onlyWhitelist = _onlyWhitelist;
}
/**
* @dev Allows the fund manager to whitelist specific addresses to control
* whos allowed to deposit into the fund
*
* @param _user The user address to whitelist
* @param _allowed The status of _user, true means allowed to deposit, false means not allowed
*/
function setWhitelistAddress(address _user, bool _allowed) external onlyOwner {
whitelist[_user] = _allowed;
}
/**
* @dev Allows the fund manager to connect to a new permitted exchange portal
*
* @param _newExchangePortalAddress The address of the new permitted exchange portal to use
*/
function setNewExchangePortal(address _newExchangePortalAddress) public onlyOwner {
// Require correct permitted address type
require(permittedAddresses.isMatchTypes(_newExchangePortalAddress, 1), "WRONG_ADDRESS");
// Set new
exchangePortal = IExchangePortal(_newExchangePortalAddress);
}
/**
* @dev Allows the fund manager to connect to a new permitted poolPortal
*
* @param _newPoolPortal The address of the new permitted pool portal to use
*/
function setNewPoolPortal(address _newPoolPortal) public onlyOwner {
// Require correct permitted address type
require(permittedAddresses.isMatchTypes(_newPoolPortal, 2), "WRONG_ADDRESS");
// Set new
poolPortal = PoolPortalInterface(_newPoolPortal);
}
/**
* @dev Allows the fund manager to connect to a new permitted defi portal
*
* @param _newDefiPortalAddress The address of the new permitted defi portal to use
*/
function setNewDefiPortal(address _newDefiPortalAddress) public onlyOwner {
// Require correct permitted address type
require(permittedAddresses.isMatchTypes(_newDefiPortalAddress, 3), "WRONG_ADDRESS");
// Set new
defiPortal = DefiPortalInterface(_newDefiPortalAddress);
}
/**
* @dev Allows the fund manager to connect to a new Oracle
*
* @param _newOracle address of new fund value Oracle contract
*/
function setNewFundValueOracle(address _newOracle) public onlyOwner {
// Require permitted Oracle
require(permittedAddresses.isMatchTypes(_newOracle, 5), "WRONG_ADDRESS");
// Set new
fundValueOracle = IFundValueOracle(_newOracle);
}
/**
* @dev This method is present in the alpha testing phase in case for some reason there are funds
* left in the SmartFund after all shares were withdrawn
*
* @param _token The address of the token to withdraw
*/
function emergencyWithdraw(address _token) external onlyOwner {
require(totalShares == 0);
if (_token == address(ETH_TOKEN_ADDRESS)) {
msg.sender.transfer(address(this).balance);
} else {
IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this)));
}
}
/**
* @dev Approve 0 for a certain address
*
* NOTE: Some ERC20 has no standard approve logic, and not allow do new approve
* if alredy approved.
*
* @param _token address of ERC20
* @param _spender address of spender
*/
function resetApprove(address _token, address _spender) external onlyOwner {
IERC20(_token).approve(_spender, 0);
}
/**
* @dev Transfers tokens to this contract and approves them to another address
*
* @param _source Token to transfer and approve
* @param _sourceAmount The amount to transfer and approve (in _source token)
* @param _to Address to approve to
*/
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
_source.transferFrom(msg.sender, address(this), _sourceAmount);
// approve
_source.approve(_to, _sourceAmount);
}
// Fallback payable function in order to be able to receive ether from other contracts
fallback() external payable {}
/**
**************************** ERC20 Compliance ****************************
**/
// Note that addressesNetDeposit does not get updated when transferring shares, since
// this is used for updating off-chain data it doesn't affect the smart contract logic,
// but is an issue that currently exists
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
uint8 public decimals = 18;
string public symbol = "FND";
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Total number of shares in existence
*/
function totalSupply() external override view returns (uint256) {
return totalShares;
}
/**
* @dev Gets the balance of the specified address.
*
* @param _who The address to query the the balance of.
*
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _who) external override view returns (uint256) {
return addressToShares[_who];
}
/**
* @dev Transfer shares for a specified address
*
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*
* @return true upon success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
require(_to != address(0));
require(_value <= addressToShares[msg.sender]);
addressToShares[msg.sender] = addressToShares[msg.sender].sub(_value);
addressToShares[_to] = addressToShares[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer shares from one address to another
*
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amount of shares to be transferred
*
* @return true upon success
*/
function transferFrom(address _from, address _to, uint256 _value) external override returns (bool) {
require(_to != address(0));
require(_value <= addressToShares[_from]);
require(_value <= allowed[_from][msg.sender]);
addressToShares[_from] = addressToShares[_from].sub(_value);
addressToShares[_to] = addressToShares[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of shares on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @param _spender The address which will spend the funds.
* @param _value The amount of shares to be spent.
*
* @return true upon success
*/
function approve(address _spender, uint256 _value) external override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of shares that an owner allowed to a spender.
*
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
*
* @return A uint256 specifying the amount of shares still available for the spender.
*/
function allowance(address _owner, address _spender) external override view returns (uint256) {
return allowed[_owner][_spender];
}
}
/*
Note: this smart fund inherits SmartFundCore and make core operations like deposit,
calculate fund value etc in ETH
*/
contract SmartFundETH is SmartFundCore {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev constructor
*
* @param _owner Address of the fund manager
* @param _name Name of the fund, required for DetailedERC20 compliance
* @param _successFee Percentage of profit that the fund manager receives
* @param _exchangePortalAddress Address of initial exchange portal
* @param _poolPortalAddress Address of initial pool portal
* @param _defiPortal Address of defi portal
* @param _permittedAddresses Address of permittedAddresses contract
* @param _fundValueOracle Address of Oracle contract
* @param _isRequireTradeVerification If true fund will require verification from Merkle White list for each new asset
* @param _cotraderGlobalConfig Address of CoTrader global config
*/
constructor(
address _owner,
string memory _name,
uint256 _successFee,
address _exchangePortalAddress,
address _poolPortalAddress,
address _defiPortal,
address _permittedAddresses,
address _fundValueOracle,
bool _isRequireTradeVerification,
address _cotraderGlobalConfig
)
SmartFundCore(
_owner,
_name,
_successFee,
_exchangePortalAddress,
_poolPortalAddress,
_defiPortal,
_permittedAddresses,
address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee),
_fundValueOracle,
_isRequireTradeVerification,
_cotraderGlobalConfig
)
public{}
/**
* @dev Deposits ether into the fund and allocates a number of shares to the sender
* depending on the current number of shares, the funds value, and amount deposited
*
* @return The amount of shares allocated to the depositor
*/
function deposit() external payable returns (uint256) {
verifyDWSender();
// Check if the sender is allowed to deposit into the fund
if (onlyWhitelist)
require(whitelist[msg.sender]);
// Require that the amount sent is not 0
require(msg.value != 0, "ZERO_DEPOSIT");
// Calculate number of shares
uint256 shares = calculateDepositToShares(msg.value);
// reset latest Oracle Caller for protect from double call
latestOracleCaller = address(0);
totalWeiDeposited += msg.value;
// If user would receive 0 shares, don't continue with deposit
require(shares != 0, "ZERO_SHARES");
// Add shares to total
totalShares = totalShares.add(shares);
// Add shares to address
addressToShares[msg.sender] = addressToShares[msg.sender].add(shares);
addressesNetDeposit[msg.sender] += int256(msg.value);
emit Deposit(msg.sender, msg.value, shares, totalShares);
return shares;
}
}
contract SmartFundETHFactory {
function createSmartFund(
address _owner,
string memory _name,
uint256 _successFee,
address _exchangePortalAddress,
address _poolPortalAddress,
address _defiPortal,
address _permittedAddresses,
address _fundValueOracle,
bool _isRequireTradeVerification,
address _cotraderGlobalConfig
)
public
returns(address)
{
SmartFundETH smartFundETH = new SmartFundETH(
_owner,
_name,
_successFee,
_exchangePortalAddress,
_poolPortalAddress,
_defiPortal,
_permittedAddresses,
_fundValueOracle,
_isRequireTradeVerification,
_cotraderGlobalConfig
);
return address(smartFundETH);
}
}
|
Facilitates a trade of the funds holdings via the exchange portal _source ERC20 token to convert from _sourceAmount Amount to convert (in _source token) _destination ERC20 token to convert to _type The type of exchange to trade with _proof Merkle tree proof (if not used just set []) _positions Merkle tree positions (if not used just set []) _additionalData For additional data (if not used just set "0x0") _minReturn Min expected amount of destination/ Make sure fund contains enough ether Call trade on ExchangePortal along with ether
|
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
uint256 _minReturn
)
external
onlyOwner
{
verifyTradeBetweenDW();
require(_minReturn > 0, "MIN_RETURN_0");
uint256 receivedAmount;
if (_source == ETH_TOKEN_ADDRESS) {
require(address(this).balance >= _sourceAmount, "NOT_ENOUGH_ETH");
receivedAmount = exchangePortal.trade.value(_sourceAmount)(
_source,
_sourceAmount,
_destination,
_type,
_proof,
_positions,
_additionalData,
isRequireTradeVerification
);
_source.approve(address(exchangePortal), _sourceAmount);
receivedAmount = exchangePortal.trade(
_source,
_sourceAmount,
_destination,
_type,
_proof,
_positions,
_additionalData,
isRequireTradeVerification
);
}
address(_source),
_sourceAmount,
address(_destination),
receivedAmount);
}
| 1,432,713
|
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/utils/Strings.sol
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/utils/EnumerableMap.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/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");
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/introspection/IERC165.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/introspection/ERC165.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.6.2;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/GSN/Context.sol
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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d9fa59f30a27f095c48b09555106fed0200654e0/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.6.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransfertFrom}, and can be used to e.g.
* implement alternative mecanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {_safeMint-address-uint256-}, with an additional `data` parameter which is forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: AAPIXToken.sol
// AAPIX Token ERC-721 for marketplace
// Indonesia Jaya Jaya Jaya
// Komunitas NFT Indonesia
pragma solidity ^0.6.0;
contract Admin is AccessControl {
bytes32 public constant WHITESLISTER = keccak256("WHITESLISTER");
bytes32 public constant BURNER = keccak256("BURNER");
modifier isWhitelister() {
require(hasRole(WHITESLISTER, msg.sender));
_;
}
modifier isBurner() {
require(hasRole(BURNER, msg.sender));
_;
}
modifier isGlobalAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE,msg.sender));
_;
}
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(WHITESLISTER, _msgSender());
_setupRole(BURNER, _msgSender());
_setRoleAdmin(DEFAULT_ADMIN_ROLE, WHITESLISTER);
_setRoleAdmin(DEFAULT_ADMIN_ROLE, BURNER);
}
}
contract AAPIX is ERC721, Ownable, Admin {
uint256 private _tokenIds;
// Mapping from tokenId to the creator's address.
mapping(uint256 => address) private tokenCreators;
// Mapping of address to boolean indicating whether the address is whitelisted
mapping(address => bool) private whitelistMap;
// flag controlling whether whitelist is enabled.
bool private whitelistEnabled = true;
// Mapping from tokenId to sale price.
mapping(uint256 => uint256) private tokenPrices;
// Mapping from tokenId to whether the token has been sold before.
mapping(uint256 => bool) private soldBefore;
// Mapping from tokenId to token owner that set the sale price.
mapping(uint256 => address) private priceSetters;
// Mapping from tokenId to the current bid amount.
mapping(uint256 => uint256) private tokenCurrentBids;
// Mapping from tokenId to the current bidder.
mapping(uint256 => address) private tokenCurrentBidders;
//mapping for paused Tokens
mapping(uint256 => bool) private tokenPaused;
// Marketplace fee paid to the owner of the contract.
uint256 private marketplaceFee = 5; // 5%
// Royalty fee paid to the creator of a token on secondary sales.
uint256 private royaltyFee = 5; // 5 %
// Primary sale fee split.
uint256 private primarySaleFee = 15; // 15 %
// Events
// SetSalePrice(_amount, _tokenId);
event SetSalePrice(uint256 _amount, uint256 _tokenId);
// Sold(msg.sender, tokenOwner, tokenPrice, _tokenId);
event Sold(address sender, address tokenOwner, uint256 tokenPrice, uint256 _tokenId);
// Bid(bidder, _newBid, _tokenId);
event Bid(address bidder, uint256 _newBid, uint256 _tokenId);
// CancelBid(bidder, bidAmount, _tokenId);
event CancelBid(address bidder, uint256 bidAmount, uint256 _tokenId);
// AcceptBid(bidder, msg.sender, bidAmount, _tokenId);
event AcceptBid(address bidder, address sender, uint256 bidAmount, uint256 _tokenId);
modifier isNotPaused(uint256 _tokenId) {
require(tokenPaused[_tokenId]==false,"token Paused");
_;
}
constructor() ERC721 ("AAPIX Store", "APIX") public {}
/*
* @dev Function to set the marketplace fee percentage.
* @param _percentage uint256 fee to take from purchases.
*/
function setMarketplaceFee(uint256 _percentage)
public onlyOwner
{
marketplaceFee = _percentage;
}
//Paused Token - freezes buy, payout, and transfer function
function pauseToken(uint256 _tokenId) public onlyOwner {
require(_exists(_tokenId) == true, "Err: token id doesn't exists");
tokenPaused[_tokenId] = true;
}
function unPauseToken(uint256 _tokenID) public onlyOwner {
require(_exists(_tokenID) == true, "Err: token id doesn't exists");
tokenPaused[_tokenID] = false;
}
/*
* @dev Function to set the royalty fee percentage.
* @param _percentage uint256 royalty fee to take split between seller and creator.
*/
function setRoyaltyFee(uint256 _percentage)
public onlyOwner
{
royaltyFee = _percentage;
}
function burn(uint256 _tokenID) public isNotPaused(_tokenID) {
require(ownerOf(_tokenID) == msg.sender || hasRole(BURNER, msg.sender), "sender is not token owner or do not have burner role" );
_burn(_tokenID);
}
/*
* @dev Function to set the primary sale fee percentage.
* @param _percentage uint256 fee to take from purchases.
*/
function setPrimarySaleFee(uint256 _percentage)
public onlyOwner
{
primarySaleFee = _percentage;
}
/**
* @dev Enable or disable the whitelist
* @param _enabled bool of whether to enable the whitelist.
*/
function setEnabledWhitelist(bool _enabled)
public isWhitelister
{
whitelistEnabled = _enabled;
}
/**
* @dev batch add addresses to the whitelist
* @param _addresses address[] of addresses to whitelist.
*/
function addToWhitelist(address[] memory _addresses)
public isWhitelister
{
// Add all _addresses.
for (uint256 i = 0; i < _addresses.length; i++) {
address _address = _addresses[i];
if (!isWhitelisted(_address)) {
whitelistMap[_address] = true;
}
}
}
/**
* @dev batch remove addresses from the whitelist
* @param _addresses address[] of addresses to whitelist.
*/
function removeFromWhitelist(address[] memory _addresses)
public isWhitelister
{
// Add all _addresses.
for (uint256 i = 0; i < _addresses.length; i++) {
address _address = _addresses[i];
if (isWhitelisted(_address)) {
whitelistMap[_address] = false;
}
}
}
/**
* @dev Returns whether the address is whitelisted
* @param _address address to check
* @return bool
*/
function isWhitelisted(address _address)
public view returns (bool)
{
if (whitelistEnabled) {
return whitelistMap[_address];
} else {
return true;
}
}
/**
* @dev Creates a new unique token.
* @param _uri string metadata uri associated with the token.
*/
function createToken(string memory _uri)
public
returns (uint256)
{
address _creator = msg.sender;
require(
isWhitelisted(_creator),
"must be whitelisted to create tokens"
);
_tokenIds++;
uint256 _newTokenId = _tokenIds;
_mint(_creator, _newTokenId);
_setTokenURI(_newTokenId, _uri);
tokenPaused[_newTokenId]=false;
tokenCreators[_newTokenId] = _creator;
return _newTokenId;
}
/*
* @dev Checks that the token owner or the token ID is approved for the Market
* @param _tokenId uint256 ID of the token
*/
modifier ownerMustHaveMarketplaceApproved(uint256 _tokenId) {
address owner = ownerOf(_tokenId);
address marketplace = address(this);
require(
isApprovedForAll(owner, marketplace) ||
getApproved(_tokenId) == marketplace,
"owner must have approved marketplace"
);
_;
}
/*
* @dev Checks that the token is owned by the sender
* @param _tokenId uint256 ID of the token
*/
modifier senderMustBeTokenOwner(uint256 _tokenId) {
address owner = ownerOf(_tokenId);
require(
owner == msg.sender,
"sender must be the token owner"
);
_;
}
/*
* @dev Checks that the token is owned by the same person who set the sale price.
* @param _tokenId address of the contract storing the token.
*/
function _priceSetterStillOwnsTheToken(uint256 _tokenId)
internal view returns (bool)
{
return ownerOf(_tokenId) == priceSetters[_tokenId];
}
/*
* @dev Set the token for sale
* @param _tokenId uint256 ID of the token
* @param _amount uint256 ether value that the item is for sale
*/
function setSalePrice(uint256 _tokenId, uint256 _amount)
public
{
setWeiSalePrice(_tokenId, _amount.mul(1000000000000000000));
}
/*
* @dev Set the token for sale
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
*/
function setWeiSalePrice(uint256 _tokenId, uint256 _amount)
public
ownerMustHaveMarketplaceApproved(_tokenId)
senderMustBeTokenOwner(_tokenId)
{
tokenPrices[_tokenId] = _amount;
priceSetters[_tokenId] = msg.sender;
emit SetSalePrice(_amount, _tokenId);
}
/*
* @dev Purchases the token if it is for sale.
* @param _tokenId uint256 ID of the token.
*/
function buy(uint256 _tokenId)
public payable
ownerMustHaveMarketplaceApproved(_tokenId)
isNotPaused(_tokenId)
{
// Check that the person who set the price still owns the token.
require(
_priceSetterStillOwnsTheToken(_tokenId),
"Current token owner must be the person to have the latest price."
);
// Check that token is for sale.
uint256 tokenPrice = tokenPrices[_tokenId];
require(tokenPrice > 0, "Tokens priced at 0 are not for sale.");
// Check that the correct ether was sent.
require(
tokenPrice == msg.value,
"Must purchase the token for the correct price"
);
address tokenOwner = ownerOf(_tokenId);
// Payout all parties.
_payout(tokenPrice, payable(tokenOwner), _tokenId);
// Transfer token.
_transfer(tokenOwner, msg.sender, _tokenId);
// Wipe the token price.
_resetTokenPrice(_tokenId);
// set the token as sold
_setTokenAsSold(_tokenId);
// if the buyer had an existing bid, return it // TODO: what if someone else had a bid?
if (_addressHasBidOnToken(msg.sender, _tokenId)) {
_refundBid(_tokenId);
}
emit Sold(msg.sender, tokenOwner, tokenPrice, _tokenId);
}
/**
* @dev Gets the sale price of the token
* @param _tokenId uint256 ID of the token
* @return sale price of the token
*/
function tokenPrice(uint256 _tokenId)
public view returns (uint256)
{
if (_priceSetterStillOwnsTheToken(_tokenId)) {
return tokenPrices[_tokenId];
}
return 0;
}
/*
* @dev Internal function to set a token as sold.
* @param _tokenId uint256 id of the token.
*/
function _setTokenAsSold(uint256 _tokenId)
internal
{
if (soldBefore[_tokenId]) {
return;
}
soldBefore[_tokenId] = true;
}
/* @dev Internal function to set token price to 0 for a give contract.
* @param _tokenId uint256 id of the token.
*/
function _resetTokenPrice(uint256 _tokenId)
internal
{
tokenPrices[_tokenId] = 0;
priceSetters[_tokenId] = address(0);
}
/////////////////////////////// PAYOUT SECTION ///////////////////////////////////////
/* @dev Internal function to pay the seller, creator, and maintainer.
* @param _amount uint256 value to be split.
* @param _seller address seller of the token.
* @param _tokenId uint256 ID of the token.
*/
function _payout(uint256 _amount, address payable _seller, uint256 _tokenId)
private
{
address payable maintainer = payable(this.owner());
address payable creator = payable(tokenCreators[_tokenId]);
bool isPrimarySale = !soldBefore[_tokenId];
uint256 marketplacePayment = _calcMarketplacePayment(isPrimarySale, _amount);
uint256 royaltyPayment = _calcRoyaltyPayment(isPrimarySale, _amount);
uint256 sellerPayment = _amount - marketplacePayment - royaltyPayment;
if (marketplacePayment > 0) {
maintainer.transfer(marketplacePayment);
}
if (royaltyPayment > 0) {
creator.transfer(royaltyPayment);
}
if (sellerPayment > 0) {
_seller.transfer(sellerPayment);
}
}
/*
* @dev Internal function to calculate Marketplace fees.
* If primary sale: fee + split with seller
otherwise: just fee.
* @param _isPrimarySale true if the token has not been sold before
* @param _amount uint256 value to be split
*/
function _calcMarketplacePayment(bool _isPrimarySale, uint256 _amount)
internal view returns (uint256)
{
if (_isPrimarySale) {
return _calcProportion(marketplaceFee, _amount) +
_calcProportion(primarySaleFee, _amount);
}
return _calcProportion(marketplaceFee, _amount);
}
/*
* @dev Internal function to calculate royalty payment.
* If primary sale: 0
* otherwise: artist royalty.
* @param _isPrimarySale true if the token has not been sold before
* @param _amount uint256 value to be split
*/
function _calcRoyaltyPayment(bool _isPrimarySale, uint256 _amount)
internal view returns (uint256)
{
if(_isPrimarySale) {
return 0;
} else {
return _calcProportion(royaltyFee, _amount);
}
}
/*
* @dev Internal function calculate proportion of a fee for a given amount.
* _amount * fee / 100
* @param _amount uint256 value to be split.
*/
function _calcProportion(uint256 fee, uint256 _amount)
internal pure returns (uint256)
{
return _amount.mul(fee).div(100);
}
/////////////////////////////// AUCTION SECTION ///////////////////////////////////////
/*
* @dev Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own.
* @param _newBidAmount uint256 value in wei to bid, plus marketplace fee.
* @param _tokenId uint256 ID of the token
*/
function bid(uint256 _tokenId)
public payable isNotPaused(_tokenId)
{
uint256 _newBid = msg.value;
address _newBidder = msg.sender;
require(
_newBid > tokenCurrentBids[_tokenId],
"Must place higher bid than existing bid."
);
require(
_newBidder != ownerOf(_tokenId),
"Bidder cannot be owner."
);
// Refund previous bidder.
_refundBid( _tokenId);
// Set the new bid.
_setBid(_newBid, _newBidder, _tokenId);
emit Bid(_newBidder, _newBid, _tokenId);
}
/**
* @dev Accept the bid on the token.
* @param _tokenId uint256 ID of the token
*/
function acceptBid(uint256 _tokenId)
public
ownerMustHaveMarketplaceApproved( _tokenId)
senderMustBeTokenOwner(_tokenId)
isNotPaused(_tokenId)
{
// Check that a bid exists.
require(
_tokenHasBid(_tokenId),
"Cannot accept a bid when there is none."
);
// Payout all parties.
(uint256 bidAmount, address bidder) = currentBidDetailsOfToken(_tokenId);
_payout(bidAmount, msg.sender, _tokenId);
// Transfer token.
safeTransferFrom(msg.sender, bidder, _tokenId);
// Wipe the token price and bid.
_resetTokenPrice(_tokenId);
_resetBid(_tokenId);
// set the token as sold
_setTokenAsSold(_tokenId);
emit AcceptBid(bidder, msg.sender, bidAmount, _tokenId);
}
/*
* @dev Cancel the bid on the token.
* @param _tokenId uint256 ID of the token.
*/
function cancelBid(uint256 _tokenId)
public
{
// Check that sender has a current bid.
address bidder = msg.sender;
require(
_addressHasBidOnToken(bidder, _tokenId),
"Cannot cancel a bid if sender hasn't made one."
);
// Refund the bidder.
_refundBid(_tokenId);
uint256 bidAmount = tokenCurrentBids[_tokenId];
emit CancelBid(bidder, bidAmount, _tokenId);
}
/*
* @dev Function to get current bid and bidder of a token.
* @param _tokenId uint256 id of the token.
*/
function currentBidDetailsOfToken(uint256 _tokenId)
public view returns (uint256, address)
{
return (
tokenCurrentBids[_tokenId],
tokenCurrentBidders[_tokenId]
);
}
/* @dev Internal function to return an existing bid on a token to the
* bidder and reset bid.
* @param _tokenId uint256 id of the token.
*/
function _refundBid(uint256 _tokenId)
internal
{
address payable currentBidder = payable(tokenCurrentBidders[_tokenId]);
uint256 _amountToRefund = tokenCurrentBids[_tokenId];
if (currentBidder == address(0)) {
return;
}
_resetBid( _tokenId);
currentBidder.transfer(_amountToRefund);
}
/*
* @dev Internal function to reset bid by setting bidder and bid to 0.
* @param _tokenId uint256 id of the token.
*/
function _resetBid(uint256 _tokenId)
internal
{
tokenCurrentBidders[_tokenId] = address(0);
tokenCurrentBids[_tokenId] = 0;
}
/*
* @dev Internal function to set a bid.
* @param _amount uint256 value in wei to bid. Does not include marketplace fee.
* @param _bidder address of the bidder.
* @param _tokenId uint256 id of the token.
*/
function _setBid(uint256 _amount, address _bidder, uint256 _tokenId)
internal
{
// Check bidder not 0 address.
require(_bidder != address(0), "Bidder cannot be 0 address.");
// Set bid.
tokenCurrentBidders[_tokenId] = _bidder;
tokenCurrentBids[_tokenId] = _amount;
}
/* @dev Internal function see if the given address has an existing bid on a token.
* @param _bidder address that may have a current bid.
* @param _tokenId uint256 id of the token.
*/
function _addressHasBidOnToken(address _bidder, uint256 _tokenId)
internal view returns (bool)
{
return tokenCurrentBidders[_tokenId] == _bidder;
}
/*
* @dev Internal function see if the token has an existing bid.
* @param _tokenId uint256 id of the token.
*/
function _tokenHasBid(uint256 _tokenId)
internal view returns (bool)
{
return tokenCurrentBidders[_tokenId] != address(0);
}
/*
* @dev External function see if the token has been paused.
* @param _tokenId uint256 id of the token.
*/
function tokenIdPauseStatus(uint256 _tokenId) external view returns (bool){
return tokenPaused[_tokenId];
}
/*
* @dev External function see how many tokens have been minted regardless of burning.
*/
function totalMinted() external view returns (uint256){
return _tokenIds;
}
}
|
Function to set the primary sale fee percentage. _percentage uint256 fee to take from purchases./
|
function setPrimarySaleFee(uint256 _percentage)
public onlyOwner
{
primarySaleFee = _percentage;
}
| 1,020,066
|
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/math/SafeMath.sol@v3.4.1-solc-0.7-2
pragma solidity ^0.7.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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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 Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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@v3.4.1-solc-0.7-2
pragma solidity ^0.7.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/interfaces/IXALD.sol
pragma solidity ^0.7.6;
interface IXALD is IERC20 {
function stake(address _recipient, uint256 _aldAmount) external;
function unstake(address _account, uint256 _xALDAmount) external;
function rebase(uint256 epoch, uint256 profit) external;
function getSharesByALD(uint256 _aldAmount) external view returns (uint256);
function getALDByShares(uint256 _sharesAmount) external view returns (uint256);
}
// File contracts/token/XALD.sol
pragma solidity ^0.7.6;
contract XALD is IXALD {
using SafeMath for uint256;
event MintShare(address recipient, uint256 share);
event BurnShare(address account, uint256 share);
event Rebase(uint256 epoch, uint256 profit);
/**
* @dev xALD balances are dynamic and are calculated based on the accounts' shares
* and the total amount of staked ALD Token. Account shares aren't normalized, so
* the contract also stores the sum of all shares to calculate each account's token
* balance which equals to:
*
* _shares[account] * _totalSupply / _totalShares
*/
mapping(address => uint256) private _shares;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _totalShares;
address public staking;
address private _initializer;
modifier onlyStaking() {
require(msg.sender == staking, "XALD: only staking contract");
_;
}
constructor() {
_initializer = msg.sender;
}
function initialize(address _staking) external {
require(_initializer == msg.sender, "XALD: only initializer");
require(_staking != address(0), "XALD: not zero address");
staking = _staking;
_initializer = address(0);
}
/**
* @dev Returns the name of the token.
*/
function name() public pure returns (string memory) {
return "staked ALD Token";
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public pure returns (string memory) {
return "xALD";
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the total shares of sALD.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _account) public view override returns (uint256) {
return getALDByShares(_shares[_account]);
}
/**
* @return the amount of shares owned by `_account`.
*/
function sharesOf(address _account) public view returns (uint256) {
return _shares[_account];
}
/**
* @dev See {IERC20-transfer}.
*/
function transfer(address _recipient, uint256 _amount) public override returns (bool) {
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address _owner, address _spender) public view override returns (uint256) {
return _allowances[_owner][_spender];
}
/**
* @dev See {IERC20-approve}.
*/
function approve(address _spender, uint256 _amount) public override returns (bool) {
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public override returns (bool) {
uint256 currentAllowance = _allowances[_sender][msg.sender];
require(currentAllowance >= _amount, "XALD: transfer amount exceeds allowance");
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, currentAllowance.sub(_amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
_approve(msg.sender, _spender, _allowances[msg.sender][_spender].add(_addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][_spender];
require(currentAllowance >= _subtractedValue, "XALD: decreased allowance below zero");
_approve(msg.sender, _spender, currentAllowance.sub(_subtractedValue));
return true;
}
function stake(address _recipient, uint256 _aldAmount) external override onlyStaking {
uint256 _sharesAmount = getSharesByALD(_aldAmount);
_totalSupply = _totalSupply.add(_aldAmount);
_mintShares(_recipient, _sharesAmount);
}
function unstake(address _account, uint256 _xALDAmount) external override onlyStaking {
uint256 _sharesAmount = getSharesByALD(_xALDAmount);
_totalSupply = _totalSupply.sub(_xALDAmount);
_burnShares(_account, _sharesAmount);
}
function rebase(uint256 epoch, uint256 profit) external override onlyStaking {
_totalSupply = _totalSupply.add(profit);
emit Rebase(epoch, profit);
}
function getSharesByALD(uint256 _aldAmount) public view override returns (uint256) {
uint256 totalPooledALD = _totalSupply;
if (totalPooledALD == 0) {
return _aldAmount;
} else {
return _aldAmount.mul(_totalShares).div(totalPooledALD);
}
}
function getALDByShares(uint256 _sharesAmount) public view override returns (uint256) {
uint256 totalShares_ = _totalShares;
if (totalShares_ == 0) {
return 0;
} else {
return _sharesAmount.mul(_totalSupply).div(totalShares_);
}
}
/**
* @dev Moves `_amount` tokens from `_sender` to `_recipient`.
*/
function _transfer(
address _sender,
address _recipient,
uint256 _amount
) internal {
uint256 _sharesToTransfer = getSharesByALD(_amount);
_transferShares(_sender, _recipient, _sharesToTransfer);
emit Transfer(_sender, _recipient, _amount);
}
/**
* @dev Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens.
*/
function _approve(
address _owner,
address _spender,
uint256 _amount
) internal {
require(_owner != address(0), "XALD: approve from the zero address");
require(_spender != address(0), "XALD: approve to the zero address");
_allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/**
* @dev Moves `_sharesAmount` shares from `_sender` to `_recipient`.
*/
function _transferShares(
address _sender,
address _recipient,
uint256 _sharesAmount
) internal {
require(_sender != address(0), "XALD: transfer from the zero address");
require(_recipient != address(0), "XALD: transfer to the zero address");
uint256 currentSenderShares = _shares[_sender];
require(_sharesAmount <= currentSenderShares, "XALD: transfer amount exceeds balance");
_shares[_sender] = currentSenderShares.sub(_sharesAmount);
_shares[_recipient] = _shares[_recipient].add(_sharesAmount);
}
/**
* @dev Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares.
*
* This doesn't increase the token total supply.
*/
function _mintShares(address _recipient, uint256 _sharesAmount) internal {
require(_recipient != address(0), "XALD: mint to the zero address");
_totalShares = _totalShares.add(_sharesAmount);
_shares[_recipient] = _shares[_recipient].add(_sharesAmount);
emit MintShare(_recipient, _sharesAmount);
}
/**
* @dev Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares.
*
* This doesn't decrease the token total supply.
*/
function _burnShares(address _account, uint256 _sharesAmount) internal {
require(_account != address(0), "XALD: burn from the zero address");
uint256 accountShares = _shares[_account];
require(_sharesAmount <= accountShares, "XALD: burn amount exceeds balance");
_totalShares = _totalShares.sub(_sharesAmount);
_shares[_account] = accountShares.sub(_sharesAmount);
emit BurnShare(_account, _sharesAmount);
}
}
|
Atomically decreases the allowance granted to `spender` by the caller./
|
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][_spender];
require(currentAllowance >= _subtractedValue, "XALD: decreased allowance below zero");
_approve(msg.sender, _spender, currentAllowance.sub(_subtractedValue));
return true;
}
| 305,859
|
pragma solidity ^0.6;
import "../../lib/SafeMath.sol";
import {Classifier64} from "./classification/Classifier.sol";
import {DataHandler64} from "./data/DataHandler.sol";
import {IncentiveMechanism64} from "./incentive/IncentiveMechanism.sol";
/**
* The main interface to sharing updatable models on the blockchain.
*/
contract CollaborativeTrainer {
// The name of the model
string public name;
// A description of the model
string public description;
// the encoder that the model uses to encoder data
string public encoder;
constructor(
string memory _name,
string memory _description,
string memory _encoder
) public {
name = _name;
description = _description;
encoder = _encoder;
}
}
/**
* The main interface to Decentralized & Collaborative AI on the Blockchain.
* For classifiers that use data with 64-bit values.
*/
// Using IoC even though it's more expensive, it's easier to work with.
// Those wishing to optimize can change the code to use inheritance and do other optimizations before deploying.
// We can also make a script that generates the required files based on several parameters.
contract CollaborativeTrainer64 is CollaborativeTrainer {
using SafeMath for uint256;
/** Data has been added. */
event AddData(
/**
* The data stored.
*/
int64[] d,
/**
* The classification for the data.
*/
uint64 c,
/**
* The time it was added.
*/
uint256 t,
/**
* The address that added the data.
*/
address indexed sender,
uint256 cost
);
DataHandler64 public dataHandler;
IncentiveMechanism64 public incentiveMechanism;
Classifier64 public classifier;
constructor(
string memory _name,
string memory _description,
string memory _encoder,
DataHandler64 _dataHandler,
IncentiveMechanism64 _incentiveMechanism,
Classifier64 _classifier
)
public
CollaborativeTrainer(_name, _description, _encoder)
{
dataHandler = _dataHandler;
incentiveMechanism = _incentiveMechanism;
classifier = _classifier;
}
/**
* Update the model.
*
* @param data A single sample of training data for the model.
* @param classification The label for `data`.
*/
function addData(int64[] memory data, uint64 classification)
public
payable
{
// how much need to be deposited
uint256 cost = incentiveMechanism.handleAddData(
msg.value,
data,
classification
);
// added time (current time)
uint256 time = dataHandler.handleAddData(
msg.sender,
cost,
data,
classification
);
// directly update the model
classifier.update(data, classification);
// Safe subtraction because cost <= msg.value.
uint256 remaining = msg.value - cost;
if (remaining > 0) {
// give back to the data provider
msg.sender.transfer(remaining);
}
// Emit here so that it's easier to catch.
emit AddData(data, classification, time, msg.sender, cost);
}
/**
* Attempt a refund for the deposit given with submitted data.
* Must be called by the address that originally submitted the data.
*
* @param data The data for which to attempt a refund.
* @param classification The label originally submitted with `data`.
* @param addedTime The time when the data was added.
*/
function refund(
int64[] memory data,
uint64 classification,
uint256 addedTime
) public {
/*
claimableAmount: The amount that can be claimed for the refund.
claimedBySubmitter: `true` if the data has already been claimed by `submitter`, otherwise `false`.
numClaims: The number of claims that have been made for the contribution before this request.
*/
(
uint256 claimableAmount,
bool claimedBySubmitter,
uint256 numClaims
) = dataHandler.handleRefund(
msg.sender,
data,
classification,
addedTime
);
// use the sample to get the prediction
// then give the incentiveMechanism to handle
uint64 prediction = classifier.predict(data);
// give the above params to incentiveMechanism
// and get the final refund amount
uint256 refundAmount = incentiveMechanism.handleRefund(
msg.sender,
data,
classification,
addedTime,
claimableAmount,
claimedBySubmitter,
prediction,
numClaims
);
msg.sender.transfer(refundAmount);
}
/**
* Report bad or old data and attempt to get a reward.
*
* @param data The data to report.
* @param classification The label originally submitted with `data`.
* @param addedTime The time when the data was added.
* @param originalAuthor The address that originally added the data.
*/
function report(
int64[] memory data,
uint64 classification,
uint256 addedTime,
address originalAuthor
) public {
/**
initialDeposit: The amount that was initially deposited when the data contribution was submitted.
claimableAmount: The amount remainining that can be claimed.
claimedByReporter: `true` if the data has already been claimed by `reporter`, otherwise `false`.
numClaims: The number of claims that have been made for the contribution before this request.
dataKey: The key to the stored data.
*/
(
uint256 initialDeposit,
uint256 claimableAmount,
bool claimedByReporter,
uint256 numClaims,
bytes32 dataKey
) = dataHandler.handleReport(
msg.sender,
data,
classification,
addedTime,
originalAuthor
);
uint64 prediction = classifier.predict(data);
// determine the reward amount
uint256 rewardAmount = incentiveMechanism.handleReport(
msg.sender,
data,
classification,
addedTime,
originalAuthor,
initialDeposit,
claimableAmount,
claimedByReporter,
prediction,
numClaims
);
// update the claimable amount after this reward (the remianing of the original deposit)
dataHandler.updateClaimableAmount(dataKey, rewardAmount);
msg.sender.transfer(rewardAmount);
}
}
|
Report bad or old data and attempt to get a reward. data The data to report. classification The label originally submitted with `data`. addedTime The time when the data was added. originalAuthor The address that originally added the data./ determine the reward amount update the claimable amount after this reward (the remianing of the original deposit)
|
function report(
int64[] memory data,
uint64 classification,
uint256 addedTime,
address originalAuthor
) public {
initialDeposit: The amount that was initially deposited when the data contribution was submitted.
claimableAmount: The amount remainining that can be claimed.
claimedByReporter: `true` if the data has already been claimed by `reporter`, otherwise `false`.
numClaims: The number of claims that have been made for the contribution before this request.
dataKey: The key to the stored data.
(
uint256 initialDeposit,
uint256 claimableAmount,
bool claimedByReporter,
uint256 numClaims,
bytes32 dataKey
) = dataHandler.handleReport(
msg.sender,
data,
classification,
addedTime,
originalAuthor
);
uint64 prediction = classifier.predict(data);
uint256 rewardAmount = incentiveMechanism.handleReport(
msg.sender,
data,
classification,
addedTime,
originalAuthor,
initialDeposit,
claimableAmount,
claimedByReporter,
prediction,
numClaims
);
dataHandler.updateClaimableAmount(dataKey, rewardAmount);
msg.sender.transfer(rewardAmount);
}
| 909,529
|
pragma solidity ^0.5.11;
contract Owned {
// State variable
address payable owner;
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call this function.");
_;
}
// constructor
constructor() public {
owner = msg.sender;
}
}
contract MoneyPotSystem is Owned {
// Custom types
struct Donation {
address payable donor;
uint amount;
}
struct MoneyPot {
uint id;
address payable author;
address payable beneficiary;
string name;
string description;
address[] donors;
mapping(uint32 => Donation) donations;
uint32 donationsCounter;
bool open;
uint feesAmount;
}
// State variables
mapping(uint => MoneyPot) public moneypots;
mapping(address => uint256[]) public addressToMoneyPot;
uint fees;
uint feesAmount;
uint moneypotCounter;
bool contractOpen;
// Modifiers
modifier onlyContractOpen() {
require(contractOpen == true);
_;
}
// Events
event createMoneyPotEvent (
uint indexed _id,
address payable indexed _author,
string _name,
uint _feesAmount,
address[] _donors
);
event chipInEvent (
uint indexed _id,
address payable indexed _donor,
uint256 _amount,
string _name,
uint _donation,
uint32 indexed _donationId
);
event closeEvent (
uint indexed _id,
address payable indexed _benefeciary,
uint256 _amount,
string _name,
address payable indexed _sender
);
event addDonorEvent(
uint indexed _id,
address payable indexed _donor
);
event feesAmountChangeEvent(
uint _oldFeesAmount,
uint _newFeesAmount
);
event withdrawFeesEvent(
uint _feesAmount
);
constructor() public {
moneypotCounter = 0;
fees = 0;
feesAmount = 6800000000000000; // 0.0068 ether
contractOpen = true;
}
function createMoneyPot(string memory _name, string memory _description, address payable _benefeciary, address[] memory _donors) onlyContractOpen public {
address[] memory donors = new address[](_donors.length + 1);
address payable author = msg.sender;
uint moneyPotId = moneypotCounter;
uint j = 0;
for (j; j < _donors.length; j++) {
require(author != _donors[j]);
donors[j] = _donors[j];
// add money pot id to donor money pot list
addressToMoneyPot[_donors[j]].push(moneyPotId);
}
// add author to donor
donors[j] = msg.sender;
// add money pot id to author money pot list
addressToMoneyPot[msg.sender].push(moneyPotId);
// Add money pot to benefeciary money pot list, if benefeciary is not author
if (msg.sender != _benefeciary) {
addressToMoneyPot[_benefeciary].push(moneyPotId);
}
moneypots[moneypotCounter] = MoneyPot(moneyPotId, author, _benefeciary, _name, _description, donors, 0, true, feesAmount);
// trigger the event
emit createMoneyPotEvent(moneypotCounter, author, _name, feesAmount, _donors);
moneypotCounter++;
}
function addDonor(uint _id, address payable _donor) public {
// we check whether the money pot exists
require(_id >= 0 && _id <= moneypotCounter);
MoneyPot storage myMoneyPot = moneypots[_id];
// we check if moneypot is open
require(myMoneyPot.open);
//check caller is author
require(myMoneyPot.author == msg.sender);
// check if donor already exist
bool donorFound = false;
for (uint j = 0; j < myMoneyPot.donors.length; j++) {
if (myMoneyPot.donors[j] == _donor) {
donorFound = true;
break;
}
}
require(!donorFound);
// Add donor
myMoneyPot.donors.push(_donor);
// le bénéficiaire possède deja l'identififiant de son pot commun
if(myMoneyPot.beneficiary != _donor) {
addressToMoneyPot[_donor].push(_id);
}
emit addDonorEvent(_id, _donor);
}
// fetch the number of money pots in the truffleContract
function getNumberOfMoneyPots() public view returns (uint256) {
return moneypotCounter;
}
function getNumberOfMyMoneyPots() public view returns (uint256) {
return addressToMoneyPot[msg.sender].length;
}
function getMyMoneyPotsIds(address who) public view returns (uint256[] memory) {
return addressToMoneyPot[who];
}
function getDonors(uint256 moneyPotId) public view returns (address[] memory) {
return moneypots[moneyPotId].donors;
}
function getDonation(uint moneyPotId, uint32 donationId) public view returns (address donor, uint amount) {
Donation storage donation = moneypots[moneyPotId].donations[donationId];
return (donation.donor, donation.amount);
}
function chipIn(uint _id) payable public {
require(moneypotCounter > 0);
// we check whether the money pot exists
require(_id >= 0 && _id <= moneypotCounter);
// we retrieve the article
MoneyPot storage myMoneyPot = moneypots[_id];
// we check if moneypot is open
require(myMoneyPot.open);
//forbidden to give if you are not a donor
bool donorFound = false;
for (uint j = 0; j < myMoneyPot.donors.length; j++) {
if (myMoneyPot.donors[j] == msg.sender) {
donorFound = true;
break;
}
}
require(donorFound);
fees = fees + myMoneyPot.feesAmount;
uint donation = msg.value - myMoneyPot.feesAmount;
// Add donation
myMoneyPot.donations[myMoneyPot.donationsCounter] = Donation(msg.sender, donation);
// trigger the event
emit chipInEvent(_id, msg.sender, msg.value, myMoneyPot.name, donation, myMoneyPot.donationsCounter);
myMoneyPot.donationsCounter += 1;
}
function withdrawFees() onlyOwner public {
owner.transfer(fees);
emit withdrawFeesEvent(fees);
fees = 0;
}
function getFeesAmount() public view returns (uint) {
return feesAmount;
}
function setFeesAmount(uint _amount) onlyOwner public {
require(feesAmount != _amount);
emit feesAmountChangeEvent(feesAmount, _amount);
feesAmount = _amount;
}
function getFees() onlyOwner public view returns (uint) {
return fees;
}
function getMoneyPotAmount(uint _id) public view returns (uint256) {
require(moneypotCounter > 0);
// we check whether the money pot exists
require(_id >= 0 && _id <= moneypotCounter);
// we retrieve the article
MoneyPot storage myMoneyPot = moneypots[_id];
uint256 amount = 0;
for (uint32 j = 0; j < myMoneyPot.donationsCounter; j++) {
amount += myMoneyPot.donations[j].amount;
}
return amount;
}
function close(uint _id) public {
require(moneypotCounter > 0);
require(_id >= 0 && _id <= moneypotCounter);
MoneyPot storage myMoneyPot = moneypots[_id];
//check caller is author or beneficiary or truffleContract owner
require(msg.sender == myMoneyPot.author || msg.sender == myMoneyPot.beneficiary || msg.sender == owner);
//check open
require(myMoneyPot.open);
uint amount = getMoneyPotAmount(myMoneyPot.id);
myMoneyPot.open = false;
myMoneyPot.beneficiary.transfer(amount);
emit closeEvent(_id, myMoneyPot.beneficiary, amount, myMoneyPot.name, msg.sender);
}
function closeAllMoneypot() onlyOwner public {
for (uint i = 0; i < moneypotCounter; i++) {
MoneyPot storage moneyPot = moneypots[i];
if (moneyPot.open) {
close(moneyPot.id);
}
}
}
function closeContract() onlyOwner public {
require(contractOpen);
contractOpen = false;
}
function openContract() onlyOwner public {
require(!contractOpen);
contractOpen = true;
}
function isOpen() public view returns (bool) {
return contractOpen;
}
// kill the smart contract
function kill() onlyOwner public {
withdrawFees();
closeAllMoneypot();
selfdestruct(owner);
}
}
|
kill the smart contract
|
function kill() onlyOwner public {
withdrawFees();
closeAllMoneypot();
selfdestruct(owner);
}
| 5,369,446
|
./partial_match/56/0xd4cC0C9a71Cb716097B753eE45FEB83a758B1fbF/sources/STEAMER.sol
|
Burn SOAK to get STEAM
|
function burnSoakForSteam(uint256 _amount) public {
require(steamerEnable, "STEAM: Steamer isn't enabled");
require(_amount > 0, "STEAM: Amount must be over 0");
require(soak.balanceOf(msg.sender) >= _amount, "STEAM: You have not enough SOAK");
soak.safeTransferFrom(address(msg.sender), burningAdress, _amount);
uint256 steamAmount = computeSteamAmount(_amount);
uint256 devMint = steamAmount.div(200);
steam.mint(address(msg.sender), steamAmount);
steam.mint(devaddr, devMint);
emit BurnSoakMintSteam(msg.sender, _amount, steamAmount);
}
| 11,059,097
|
./partial_match/1/0xA34757fC1e8EAD538C4ef2Ef23286517A7a9d0a7/sources/DexnesCaptain.sol
|
Migrate lp token to another DEXNES lp contract. Can only be called by the owner. Tip: Reuse the contract used by SushiSwap on their successful migration
|
function migrate(uint256 _pid) public onlyOwner {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
| 2,653,275
|
./partial_match/1/0x21B8bfbbefc9E2b9A994871Ecd742A5132B98AeD/sources/CryptoRealEstate.sol
|
Withdraws the Eth balance from the contract./
|
function withdrawEth() external onlyOwner {
uint256 amount = address(this).balance;
address payable to = payable(msg.sender);
to.sendValue(amount);
emit WithdrawedEth(to, amount);
}
| 4,289,844
|
pragma solidity >=0.4.4 <0.7.0;
contract causasBeneficas{
//Declaraciones necesarias
struct Causa{
uint Id;
string name;
uint precio_objetivo;
uint cantidad_recaudada;
}
uint contador_causas = 0;
mapping (string => Causa) causas;
//Permite dar de alta una nueva causa
function nuevaCausa( string memory _nombre, uint _precio_objetivo ) public payable {
contador_causas = contador_causas++;
Causa memory causa = Causa(contador_causas, _nombre, _precio_objetivo, 0);
causas[_nombre] = causa;
//causas[_nombre] = Causa(contador_causas, _nombre, _precio_objetivo, 0);
}
//Esta funcion nos devuelve true en casso de que podamos donar a una causa
function objetivoCumplido(string memory _nombre, uint _donar) private view returns(bool){
bool flag = false;
Causa memory causa = causas[_nombre];
if(causa.precio_objetivo >= causa.cantidad_recaudada + _donar){
flag = true;
}
return flag;
}
//Esta funcion nos permite donar a una Causa
function donar(string memory _nombre, uint _cantidad) public returns(bool) {
bool aceptar_donacion = true;
if(objetivoCumplido(_nombre,_cantidad)){
causas[_nombre].cantidad_recaudada = causas[_nombre].cantidad_recaudada + _cantidad;
}else {
aceptar_donacion = false;
}
return aceptar_donacion;
}
//Esta funcion nos dice si hemos llegado al precio objetivo
function comprobar_causa(string memory _nombre) public view returns(bool, uint) {
bool limite_alcanzado = false;
Causa memory causa = causas[_nombre];
if(causa.cantidad_recaudada >= causa.precio_objetivo){
limite_alcanzado = true;
}
return (limite_alcanzado, causa.cantidad_recaudada);
}
}
|
Esta funcion nos dice si hemos llegado al precio objetivo
|
function comprobar_causa(string memory _nombre) public view returns(bool, uint) {
bool limite_alcanzado = false;
Causa memory causa = causas[_nombre];
if(causa.cantidad_recaudada >= causa.precio_objetivo){
limite_alcanzado = true;
}
return (limite_alcanzado, causa.cantidad_recaudada);
}
| 5,458,371
|
./partial_match/42/0x4ffADC639B57e864150ff98a55D249fed53fa63B/sources/ZuniBadge.sol
|
Externally check permissions using the Enum self - Rights struct containing the permissions permission - The permission to check return Boolean true if it has the permission/
|
function hasPermission(Rights calldata self, Permissions permission)
external
pure
returns (bool)
{
if (Permissions.PAUSE_SWAPPING == permission) {
return self.canPauseSwapping;
return self.canChangeSwapFee;
return self.canChangeWeights;
return self.canAddRemoveTokens;
return self.canWhitelistLPs;
return self.canChangeCap;
}
}
| 3,448,934
|
./full_match/1/0x92Cc4c289cA8821A233A404c58479a0f209cF285/sources/contracts/libraries/LmTick.sol
|
Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa self The mapping containing all tick information for initialized ticks tick The tick that will be updated tickCurrent The current tick liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) rewardGrowthGlobalX128 The all-time global reward growth, per unit of liquidity upper true for updating a position's upper tick, or false for updating a position's lower tick maxLiquidity The maximum liquidity allocation for a single tick return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa by convention, we assume that all growth before a tick was initialized happened _below_ the tick
|
function update(
mapping(int24 => LmTick.Info) storage self,
int24 tick,
int24 tickCurrent,
int128 liquidityDelta,
uint256 rewardGrowthGlobalX128,
bool upper,
uint128 maxLiquidity
) internal returns (bool flipped) {
LmTick.Info storage info = self[tick];
uint128 liquidityGrossBefore = info.liquidityGross;
uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);
require(liquidityGrossAfter <= maxLiquidity, 'LO');
flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);
if (liquidityGrossBefore == 0) {
if (tick <= tickCurrent) {
info.rewardGrowthOutsideX128 = rewardGrowthGlobalX128;
}
}
info.liquidityGross = liquidityGrossAfter;
? int256(info.liquidityNet).sub(liquidityDelta).toInt128()
: int256(info.liquidityNet).add(liquidityDelta).toInt128();
}
| 4,989,625
|
./full_match/80001/0x68B870eC968abB8974398c5B7d43D19317f7C5fD/sources/MasterChef.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accStopPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeStopTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStopPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 9,496,388
|
/**
*Submitted for verification at Etherscan.io on 2020-10-22
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
//
/**
* @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);
}
//
/**
* @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;
}
}
//
/**
* @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);
}
}
}
}
//
/**
* @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");
}
}
}
//
/**
* @notice Interface for Curve.fi's REN pool.
* Note that we are using array of 2 as Curve's REN pool contains only WBTC and renBTC.
*/
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// renBTC pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
}
//
/**
* @notice Interface for the migrator.
*/
interface IMigrator {
/**
* @dev What token is migrated from.
*/
function want() external view returns (address);
/**
* @dev What token is migrated to.
*/
function get() external view returns (address);
/**
* @dev Performs the token migration.
*/
function migrate() external;
}
//
/**
* @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;
}
}
//
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
* Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
//
/**
* @notice Interface for ERC20 token which supports minting new tokens.
*/
interface IERC20Mintable is IERC20 {
function mint(address _user, uint256 _amount) external;
}
//
/**
* @notice Interface for ERC20 token which supports mint and burn.
*/
interface IERC20MintableBurnable is IERC20Mintable {
function burn(uint256 _amount) external;
function burnFrom(address _user, uint256 _amount) external;
}
//
/**
* @notice ACoconut swap.
*/
contract ACoconutSwap is Initializable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Token swapped between two underlying tokens.
*/
event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought);
/**
* @dev New pool token is minted.
*/
event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount);
/**
* @dev Pool token is redeemed.
*/
event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount);
/**
* @dev Fee is collected.
*/
event FeeCollected(address indexed feeRecipient, uint256 feeAmount);
uint256 public constant feeDenominator = 10 ** 10;
address[] public tokens;
uint256[] public precisions; // 10 ** (18 - token decimals)
uint256[] public balances; // Converted to 10 ** 18
uint256 public mintFee; // Mint fee * 10**10
uint256 public swapFee; // Swap fee * 10**10
uint256 public redeemFee; // Redeem fee * 10**10
address public feeRecipient;
address public poolToken;
uint256 public totalSupply; // The total amount of pool token minted by the swap.
// It might be different from the pool token supply as the pool token can have multiple minters.
address public governance;
mapping(address => bool) public admins;
bool public paused;
uint256 public initialA;
/**
* @dev Initialize the ACoconut Swap.
*/
function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees,
address _poolToken, uint256 _A) public initializer {
require(_tokens.length == _precisions.length, "input mismatch");
require(_fees.length == 3, "no fees");
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != address(0x0), "token not set");
require(_precisions[i] != 0, "precision not set");
balances.push(0);
}
require(_poolToken != address(0x0), "pool token not set");
governance = msg.sender;
feeRecipient = msg.sender;
tokens = _tokens;
precisions = _precisions;
mintFee = _fees[0];
swapFee = _fees[1];
redeemFee = _fees[2];
poolToken = _poolToken;
initialA = _A;
// The swap must start with paused state!
paused = true;
}
/**
* @dev Returns the current value of A. This method might be updated in the future.
*/
function getA() public view returns (uint256) {
return initialA;
}
/**
* @dev Computes D given token balances.
* @param _balances Normalized balance of each token.
* @param _A Amplification coefficient from getA()
*/
function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) {
uint256 sum = 0;
uint256 i = 0;
uint256 Ann = _A;
for (i = 0; i < _balances.length; i++) {
sum = sum.add(_balances[i]);
Ann = Ann.mul(_balances.length);
}
if (sum == 0) return 0;
uint256 prevD = 0;
uint256 D = sum;
for (i = 0; i < 255; i++) {
uint256 pD = D;
for (uint256 j = 0; j < _balances.length; j++) {
// pD = pD * D / (_x * balance.length)
pD = pD.mul(D).div(_balances[j].mul(_balances.length));
}
prevD = D;
// D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD)
D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD)));
if (D > prevD) {
if (D - prevD <= 1) break;
} else {
if (prevD - D <= 1) break;
}
}
return D;
}
/**
* @dev Computes token balance given D.
* @param _balances Converted balance of each token except token with index _j.
* @param _j Index of the token to calculate balance.
* @param _D The target D value.
* @param _A Amplification coeffient.
* @return Converted balance of the token with index _j.
*/
function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) {
uint256 c = _D;
uint256 S_ = 0;
uint256 Ann = _A;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
Ann = Ann.mul(_balances.length);
if (i == _j) continue;
S_ = S_.add(_balances[i]);
// c = c * D / (_x * N)
c = c.mul(_D).div(_balances[i].mul(_balances.length));
}
// c = c * D / (Ann * N)
c = c.mul(_D).div(Ann.mul(_balances.length));
// b = S_ + D / Ann
uint256 b = S_.add(_D.div(Ann));
uint256 prevY = 0;
uint256 y = _D;
// 255 since the result is 256 digits
for (i = 0; i < 255; i++) {
prevY = y;
// y = (y * y + c) / (2 * y + b - D)
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D));
if (y > prevY) {
if (y - prevY <= 1) break;
} else {
if (prevY - y <= 1) break;
}
}
return y;
}
/**
* @dev Compute the amount of pool token that can be minted.
* @param _amounts Unconverted token balances.
* @return The amount of pool token minted.
*/
function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amounts.length == _balances.length, "invalid amount");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (address(this).balance == 0) continue; //inject PRESENT ETHER
// balance = balance + amount * precision
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD);
uint256 feeAmount = 0;
if (mintFee > 0) {
feeAmount = mintAmount.mul(mintFee).div(feeDenominator);
mintAmount = mintAmount.sub(feeAmount);
}
return (mintAmount, feeAmount);
}
/**
* @dev Mints new pool token.
* @param _amounts Unconverted token balances used to mint pool token.
* @param _minMintAmount Minimum amount of pool token to mint.
*/
function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can mint.
require(!paused || admins[msg.sender], "paused");
require(_balances.length == _amounts.length, "invalid amounts");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (address(this).balance == 0) { //inject PRESENT ETHER
// Initial deposit requires all tokens provided!
require(oldD > 0, "zero amount");
continue;
}
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD);
uint256 fee = mintFee;
uint256 feeAmount;
if (fee > 0) {
feeAmount = mintAmount.mul(fee).div(feeDenominator);
mintAmount = mintAmount.sub(feeAmount);
}
require(mintAmount >= _minMintAmount, "fewer than expected");
// Transfer tokens into the swap
for (i = 0; i < _amounts.length; i++) {
if (address(this).balance == 0) continue; //inject PRESENT ETHER
// Update the balance in storage
balances[i] = _balances[i];
IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
totalSupply = newD;
IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount);
IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount);
emit Minted(msg.sender, mintAmount, _amounts, feeAmount);
}
/**
* @dev Computes the output amount after the swap.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @return Unconverted amount of token _j to swap out.
*/
function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) {
uint256[] memory _balances = balances;
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
// balance[i] = balance[i] + dx * precisions[i]
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
// dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
if (swapFee > 0) {
dy = dy.sub(dy.mul(swapFee).div(feeDenominator));
}
return dy;
}
/**
* @dev Exchange between two underlying tokens.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @param _minDy Minimum token _j to swap out in converted balance.
*/
function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can swap.
require(!paused || admins[msg.sender], "paused");
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
// balance[i] = balance[i] + dx * precisions[i]
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
// dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
// Update token balance in storage
balances[_j] = y;
balances[_i] = _balances[_i];
uint256 fee = swapFee;
if (fee > 0) {
dy = dy.sub(dy.mul(fee).div(feeDenominator));
}
require(dy >= _minDy, "fewer than expected");
IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx);
// Important: When swap fee > 0, the swap fee is charged on the output token.
// Therefore, balances[j] < tokens[j].balanceOf(this)
// Since balances[j] is used to compute D, D is unchanged.
// collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this)
// into pool token as fees!
IERC20(tokens[_j]).safeTransfer(msg.sender, dy);
emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy);
}
/**
* @dev Computes the amounts of underlying tokens when redeeming pool token.
* @param _amount Amount of pool tokens to redeem.
* @return Amounts of underlying tokens redeemed.
*/
function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) {
uint256[] memory _balances = balances;
require(_amount > 0, "zero amount");
uint256 D = totalSupply;
uint256[] memory amounts = new uint256[](_balances.length);
uint256 feeAmount = 0;
if (redeemFee > 0) {
feeAmount = _amount.mul(redeemFee).div(feeDenominator);
// Redemption fee is charged with pool token before redemption.
_amount = _amount.sub(feeAmount);
}
for (uint256 i = 0; i < _balances.length; i++) {
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use
// D in case we have multiple minters on the pool token.
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
}
return (amounts, feeAmount);
}
/**
* @dev Redeems pool token to underlying tokens proportionally.
* @param _amount Amount of pool token to redeem.
* @param _minRedeemAmounts Minimum amount of underlying tokens to get.
*/
function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
require(_amount > 0, "zero amount");
require(_balances.length == _minRedeemAmounts.length, "invalid mins");
uint256 D = totalSupply;
uint256[] memory amounts = new uint256[](_balances.length);
uint256 fee = redeemFee;
uint256 feeAmount;
if (fee > 0) {
feeAmount = _amount.mul(fee).div(feeDenominator);
// Redemption fee is paid with pool token
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
_amount = _amount.sub(feeAmount);
}
for (uint256 i = 0; i < _balances.length; i++) {
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use
// D in case we have multiple minters on the pool token.
uint256 tokenAmount = _balances[i].mul(_amount).div(D);
// Important: Underlying tokens must convert back to original decimals!
amounts[i] = tokenAmount.div(precisions[i]);
require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected");
// Updates the balance in storage
balances[i] = _balances[i].sub(tokenAmount);
IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]);
}
totalSupply = D.sub(_amount);
// After reducing the redeem fee, the remaining pool tokens are burned!
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
}
/**
* @dev Computes the amount when redeeming pool token to one specific underlying token.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the underlying token to redeem to.
* @return Amount of underlying token that can be redeem to.
*/
function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amount > 0, "zero amount");
require(_i < _balances.length, "invalid token");
uint256 A = getA();
uint256 D = totalSupply;
uint256 feeAmount = 0;
if (redeemFee > 0) {
feeAmount = _amount.mul(redeemFee).div(feeDenominator);
// Redemption fee is charged with pool token before redemption.
_amount = _amount.sub(feeAmount);
}
// The pool token amount becomes D - _amount
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
// dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors
uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]);
return (dy, feeAmount);
}
/**
* @dev Redeem pool token to one specific underlying token.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the token to redeem to.
* @param _minRedeemAmount Minimum amount of the underlying token to redeem to.
*/
function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
require(_amount > 0, "zero amount");
require(_i < _balances.length, "invalid token");
uint256 A = getA();
uint256 D = totalSupply;
uint256 fee = redeemFee;
uint256 feeAmount = 0;
if (fee > 0) {
// Redemption fee is charged with pool token before redemption.
feeAmount = _amount.mul(fee).div(feeDenominator);
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
_amount = _amount.sub(feeAmount);
}
// y is converted(18 decimals)
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
// dy is not converted
// dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors
uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]);
require(dy >= _minRedeemAmount, "fewer than expected");
// Updates token balance in storage
balances[_i] = y;
uint256[] memory amounts = new uint256[](_balances.length);
amounts[_i] = dy;
IERC20(tokens[_i]).safeTransfer(msg.sender, dy);
totalSupply = D.sub(_amount);
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
}
/**
* @dev Compute the amount of pool token that needs to be redeemed.
* @param _amounts Unconverted token balances.
* @return The amount of pool token that needs to be redeemed.
*/
function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amounts.length == balances.length, "length not match");
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
if (address(this).balance == 0) continue; //inject PRESENT ETHER
// balance = balance + amount * precision
_balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be smaller than or equal to oldD
uint256 redeemAmount = oldD.sub(newD);
uint256 feeAmount = 0;
if (redeemFee > 0) {
redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee));
feeAmount = redeemAmount.sub(oldD.sub(newD));
}
return (redeemAmount, feeAmount);
}
/**
* @dev Redeems underlying tokens.
* @param _amounts Amounts of underlying tokens to redeem to.
* @param _maxRedeemAmount Maximum of pool token to redeem.
*/
function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant {
uint256[] memory _balances = balances;
require(_amounts.length == balances.length, "length not match");
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (address(this).balance == 0) continue; //inject PRESENT ETHER
// balance = balance + amount * precision
_balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be smaller than or equal to oldD
uint256 redeemAmount = oldD.sub(newD);
uint256 fee = redeemFee;
uint256 feeAmount = 0;
if (fee > 0) {
redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee));
feeAmount = redeemAmount.sub(oldD.sub(newD));
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
}
require(redeemAmount <= _maxRedeemAmount, "more than expected");
// Updates token balances in storage.
balances = _balances;
uint256 burnAmount = redeemAmount.sub(feeAmount);
totalSupply = oldD.sub(burnAmount);
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, burnAmount);
for (i = 0; i < _balances.length; i++) {
if (address(this).balance == 0) continue; //inject PRESENT ETHER
IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]);
}
emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount);
}
/**
* @dev Return the amount of fee that's not collected.
*/
function getPendingFeeAmount() external view returns (uint256) {
uint256[] memory _balances = balances;
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
_balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]);
}
uint256 newD = _getD(_balances, A);
return newD.sub(oldD);
}
/**
* @dev Collect fee based on the token balance difference.
*/
function collectFee() external returns (uint256) {
require(admins[msg.sender], "not admin");
uint256[] memory _balances = balances;
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
_balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]);
}
uint256 newD = _getD(_balances, A);
uint256 feeAmount = newD.sub(oldD);
if (address(this).balance == 0) return 0; //inject PRESENT ETHER
balances = _balances;
totalSupply = newD;
address _feeRecipient = feeRecipient;
IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount);
emit FeeCollected(_feeRecipient, feeAmount);
return feeAmount;
}
/**
* @dev Updates the govenance address.
*/
function setGovernance(address _governance) external {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Updates the mint fee.
*/
function setMintFee(uint256 _mintFee) external {
require(msg.sender == governance, "not governance");
mintFee = _mintFee;
}
/**
* @dev Updates the swap fee.
*/
function setSwapFee(uint256 _swapFee) external {
require(msg.sender == governance, "not governance");
swapFee = _swapFee;
}
/**
* @dev Updates the redeem fee.
*/
function setRedeemFee(uint256 _redeemFee) external {
require(msg.sender == governance, "not governance");
redeemFee = _redeemFee;
}
/**
* @dev Updates the recipient of mint/swap/redeem fees.
*/
function setFeeRecipient(address _feeRecipient) external {
require(msg.sender == governance, "not governance");
require(_feeRecipient != address(0x0), "fee recipient not set");
feeRecipient = _feeRecipient;
}
/**
* @dev Updates the pool token.
*/
function setPoolToken(address _poolToken) external {
require(msg.sender == governance, "not governance");
require(_poolToken != address(0x0), "pool token not set");
poolToken = _poolToken;
}
/**
* @dev Pause mint/swap/redeem actions. Can unpause later.
*/
function pause() external {
require(msg.sender == governance, "not governance");
require(!paused, "paused");
paused = true;
}
/**
* @dev Unpause mint/swap/redeem actions.
*/
function unpause() external {
require(msg.sender == governance, "not governance");
require(paused, "not paused");
paused = false;
}
/**
* @dev Updates the admin role for the address.
* @param _account Address to update admin role.
* @param _allowed Whether the address is granted the admin role.
*/
function setAdmin(address _account, bool _allowed) external {
require(msg.sender == governance, "not governance");
require(_account != address(0x0), "account not set");
admins[_account] = _allowed;
}
}
//
contract CurveRenCrvMigrator is IMigrator {
using SafeERC20 for IERC20;
address public constant override want = address(0x49849C98ae39Fff122806C06791Fa73784FB3675); // renCrv token
address public constant override get = address(0xeF6e45af9a422c5469928F927ca04ed332322e2e); // acBTC
address public constant wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // WBTC token
address public constant renbtc = address(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D); // renBTC token
address public constant acSwap = address(0x73FddFb941c11d16C827169Bb94aCC227841C396); // ACoconutSwap (proxy)
address public constant acVault = address(0x1eB47C01cfAb26D2346B449975b7BF20a34e0d45); // acBTC vault
address public constant curve = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); // REN swap
/**
* @dev Performs the token migration. Only acBTC vault can trigger the migration.
*/
function migrate() public override {
require(msg.sender == acVault, "not vault");
uint256 _want = IERC20(want).balanceOf(address(this)); // renCrv balance
IERC20(want).safeApprove(curve, _want);
if (_want > 0) {
ICurveFi(curve).remove_liquidity(_want, [uint256(0), 0]);
}
uint256 _wbtc = IERC20(wbtc).balanceOf(address(this));
uint256 _renbtc = IERC20(renbtc).balanceOf(address(this));
// The initial deposit requires both WBTC and RenBTC.
if (_wbtc > 0 && _renbtc > 0) {
IERC20(wbtc).safeApprove(acSwap, _wbtc);
IERC20(renbtc).safeApprove(acSwap, _renbtc);
// WBTC is the first token and renBTC is the second!
uint256[] memory amounts = new uint256[](2);
amounts[0] = _wbtc;
amounts[1] = _renbtc;
ACoconutSwap(acSwap).mint(amounts, 0);
}
uint256 _get = IERC20(get).balanceOf(address(this)); // acBTC balance
if (_get > 0) {
IERC20(get).safeTransfer(acVault, _get);
}
}
}
|
Exchange between two underlying tokens. _i Token index to swap in. _j Token index to swap out. _dx Unconverted amount of token _i to swap in. _minDy Minimum token _j to swap out in converted balance./ If swap is paused, only admins can swap. balance[i] = balance[i] + dx precisions[i] dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors Update token balance in storage
|
function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant {
uint256[] memory _balances = balances;
require(!paused || admins[msg.sender], "paused");
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
balances[_j] = y;
balances[_i] = _balances[_i];
uint256 fee = swapFee;
if (fee > 0) {
dy = dy.sub(dy.mul(fee).div(feeDenominator));
}
require(dy >= _minDy, "fewer than expected");
IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx);
emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy);
IERC20(tokens[_j]).safeTransfer(msg.sender, dy);
}
| 12,730,953
|
./partial_match/1/0xd8bcFD9dE4aEF52Eb92Faa56bFc7A75016bE127b/sources/TelegramDiceRoulette.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
WELCOME TO ZE DICE ROULETTE.
}
| 4,332,323
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import './interfaces/Burnable.sol';
import "./libraries/SafeMath.sol";
import './tokens/PausableToken.sol';
contract SoldiersPresaleToken is PausableToken, Burnable {
using SafeMath for uint;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
uint public constant MAX_LIQUIDITY_SUPPLY = 5000;
uint public constant MAX_PRESALE_SLOT1_SUPPLY = 5000;
uint public constant MAX_PRESALE_SLOT2_SUPPLY = 20000;
uint public constant MAX_PRESALE_SLOT3_SUPPLY = 30000;
string public constant override name = 'Pre-Sale SOLDIERS Token';
string public constant override symbol = '$pSLDRS';
uint8 public constant override decimals = 6;
// Crowdsale Stages
enum CrowdsaleStage { SALE_NOTSTARTED, PRESALE_STAGE1, PRESALE_STAGE2, PRESALE_STAGE3, SALE }
// The busd token
address public busdToken;
// Address where BUSD funds are collected
address public wallet;
// How many token units a buyer gets per BUSD in wei
uint public preSaleSlot1rate = 10000000000000;
uint public presaleSlot1StartTime;
uint public presaleSlot1EndTime;
uint public preSaleSlot2rate = 15000000000000;
uint public presaleSlot2StartTime;
uint public presaleSlot2EndTime;
uint public preSaleSlot3rate = 20000000000000;
uint public presaleSlot3StartTime;
uint public presaleSlot3EndTime;
uint public saleStartTime;
mapping(address => bool) public whitelist;
constructor(
uint256 _initialSupply,
uint _saleStartTime,
address _busdToken,
address _wallet
) {
require(keccak256(abi.encodePacked(IERC20(_busdToken).symbol())) == keccak256(abi.encodePacked("BUSD")));
require(_wallet != address(0));
busdToken = _busdToken;
wallet = _wallet;
saleStartTime = _saleStartTime;
presaleSlot1StartTime = _saleStartTime - (21 * 24 * 60 * 60);
presaleSlot1EndTime = presaleSlot1StartTime + (7 * 24 * 60 * 60);
presaleSlot2StartTime = _saleStartTime - (14 * 24 * 60 * 60);
presaleSlot2EndTime = presaleSlot2StartTime + (7 * 24 * 60 * 60);
presaleSlot3StartTime = _saleStartTime - (7 * 24 * 60 * 60);
presaleSlot3EndTime = presaleSlot3StartTime + (7 * 24 * 60 * 60);
_mint(owner(), _initialSupply);
}
function approve(address _spender, uint256 _value) public override returns (bool) {
return super.approve(_spender, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public override returns (bool) {
return super.transfer(_to, _value);
}
function burn(address _holder, uint _value) public onlyOwner override returns (bool) {
return _burn(_holder, _value);
}
/**
* @dev Function returns stage of sale at any point in time
*/
function getStageOfSale() external view returns(CrowdsaleStage) {
if(block.timestamp < presaleSlot1StartTime) {
return CrowdsaleStage.SALE_NOTSTARTED;
} else if(block.timestamp >= presaleSlot1StartTime && block.timestamp < presaleSlot1EndTime) {
return CrowdsaleStage.PRESALE_STAGE1;
} else if(block.timestamp >= presaleSlot2StartTime && block.timestamp < presaleSlot2EndTime) {
return CrowdsaleStage.PRESALE_STAGE2;
} else if(block.timestamp >= presaleSlot3StartTime && block.timestamp < presaleSlot3EndTime) {
return CrowdsaleStage.PRESALE_STAGE3;
} else if(block.timestamp >= saleStartTime) {
return CrowdsaleStage.SALE;
}
return CrowdsaleStage.SALE_NOTSTARTED;
}
/**
* @dev Function to buy pre sale token in BUSD in wei
* @param _numberOfUnits Number of pSLDRs in smallest unit to buy
*/
function buy(uint _numberOfUnits) external {
require(block.timestamp >= presaleSlot1StartTime, 'Presale Not started');
require(_numberOfUnits > 0, 'Number of Units is Zero');
uint _rate;
uint _soldTokens = totalSupply - balanceOf[wallet];
if(block.timestamp < presaleSlot1EndTime) {
_rate = preSaleSlot1rate;
require(_soldTokens + _numberOfUnits <= MAX_PRESALE_SLOT1_SUPPLY.mul(multiplier()), 'Presale Slot1 limit crossed');
} else if(block.timestamp >= presaleSlot2StartTime && block.timestamp < presaleSlot2EndTime) {
_rate = preSaleSlot2rate;
require(whitelist[msg.sender], 'Not Whitelisted');
require(_soldTokens + _numberOfUnits <=
(MAX_PRESALE_SLOT1_SUPPLY + MAX_PRESALE_SLOT2_SUPPLY).mul(multiplier()), 'Presale Slot2 limit crossed');
} else if(block.timestamp >= presaleSlot3StartTime && block.timestamp < presaleSlot3EndTime) {
_rate = preSaleSlot3rate;
require(_soldTokens + _numberOfUnits <=
(MAX_PRESALE_SLOT1_SUPPLY + MAX_PRESALE_SLOT2_SUPPLY + MAX_PRESALE_SLOT3_SUPPLY).mul(multiplier()), 'Presale Slot3 limit crossed');
}
uint _amount = _numberOfUnits.mul(_rate);
IERC20(busdToken).transferFrom(msg.sender, wallet, _amount);
_transfer(wallet, msg.sender, _numberOfUnits);
}
/**
* @dev Function to set sale start time
* @param _saleStartTimestamp sale start time
*/
function setSaleStartTime(uint _saleStartTimestamp) external onlyOwner {
saleStartTime = _saleStartTimestamp;
}
/**
* @dev Function to set pre sale slot1 rate in BUSD in wei
* @param _rate Amount of BUSD in wei per small unit to buy
*/
function setPreSaleSlot1Rate(uint _rate) external onlyOwner {
require(_rate > 0, 'Presale Slot1 Rate is 0');
preSaleSlot1rate = _rate;
}
/**
* @dev Function to set pre-sale slot1 window w.r.t sale start time
* @param _daysPrior number of days prior to sale start time
* @param _durationInSecs duration of presale in seconds or epoch from slot1 start time
*/
function setPreSaleSlot1Window(uint _daysPrior, uint _durationInSecs) external onlyOwner {
presaleSlot1StartTime = saleStartTime - (_daysPrior * 24 * 60 * 60);
presaleSlot1EndTime = presaleSlot1StartTime + _durationInSecs;
require(presaleSlot1EndTime <= presaleSlot2StartTime, 'Presale Slot1 end time greater than slot2 start time');
}
/**
* @dev Function to set pre sale slot1 rate in BUSD in wei
* @param _rate Amount of BUSD in wei per small unit to buy
*/
function setPreSaleSlot2Rate(uint _rate) external onlyOwner {
require(_rate > 0, 'Presale Slot2 Rate is 0');
preSaleSlot2rate = _rate;
}
/**
* @dev Function to set pre-sale slot2 window w.r.t sale start time
* @param _daysPrior number of days prior to sale start time
* @param _durationInSecs duration of presale in seconds or epoch from slot1 start time
*/
function setPreSaleSlot2Window(uint _daysPrior, uint _durationInSecs) external onlyOwner {
presaleSlot2StartTime = saleStartTime - (_daysPrior * 24 * 60 * 60);
presaleSlot2EndTime = presaleSlot2StartTime + _durationInSecs;
require(presaleSlot2EndTime <= presaleSlot3StartTime, 'Presale slot2 end time greater than slot3 start time');
}
/**
* @dev Function to set public presale or slot3 rate in BUSD in wei
* @param _rate Amount of BUSD in wei per small unit to buy
*/
function setPreSaleSlot3Rate(uint _rate) external onlyOwner {
require(_rate > 0, 'Presale Slot2 Rate is 0');
preSaleSlot3rate = _rate;
}
/**
* @dev Function to set pre-sale slot3 window w.r.t sale start time
* @param _daysPrior number of days prior to sale start time
* @param _durationInSecs duration of presale in seconds or epoch from slot3 start time
*/
function setPreSaleSlot3Window(uint _daysPrior, uint _durationInSecs) external onlyOwner {
presaleSlot3StartTime = saleStartTime - (_daysPrior * 24 * 60 * 60);
presaleSlot3EndTime = presaleSlot3StartTime + _durationInSecs;
require(presaleSlot3EndTime <= saleStartTime, 'Presale Slot3 end time greater than sale time');
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return success if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
require(!whitelist[addr], 'Address already whitelisted');
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return success if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
return true;
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return success if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
require(whitelist[addr], 'Address not whitelisted');
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return success if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
return true;
}
function multiplier() internal pure returns(uint) {
return 10**decimals;
}
}
|
add addresses to the whitelist addrs addresses return success if at least one address was added to the whitelist, false if all addresses were already in the whitelist/
|
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
return true;
}
| 5,402,572
|
/**
*Submitted for verification at Etherscan.io on 2021-07-22
*/
/*
Website: uPlexa.com
$$$$$$$\ $$\
$$ __$$\ $$ |
$$\ $$\ $$ | $$ |$$ | $$$$$$\ $$\ $$\ $$$$$$\
$$ | $$ |$$$$$$$ |$$ |$$ __$$\ \$$\ $$ |\____$$\
$$ | $$ |$$ ____/ $$ |$$$$$$$$ | \$$$$ / $$$$$$$ |
$$ | $$ |$$ | $$ |$$ ____| $$ $$< $$ __$$ |
\$$$$$$ |$$ | $$ |\$$$$$$$\ $$ /\$$\\$$$$$$$ |
\______/ \__| \__| \_______|\__/ \__|\_______|
*/
pragma solidity ^0.6.12;
/*
* @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;
}
}
/**
* @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);
/**
* Burn. Called by public function, allowing users to burn their
* wUPX for swapping to UPX. Only use this with the Bridge.
*/
event Burn(address indexed burner, uint256 value, string note);
/**
* @dev Emitted when 'taxWallet' is updated to a new wallet
*/
event TaxWalletTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Emitted when acount is updated to be excluded
*/
event ExcludedAccount(address indexed account);
/**
* @dev Emitted when account is updated to be included
*/
event IncludedAccount(address indexed account);
}
/**
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @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;
}
}
/**
* @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;
mapping (address => bool) private _isExcluded;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint256 private _tFeeTotal;
address private _taxWallet;
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;
_taxWallet = 0x502bEdE43D884Da820657a0f67bcbaad25139CeE;
_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}.
*OwnershipTransferred
* 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) {
// 1% Tax gets sent to upxReaper contract.
// Since token is deployed BEFORE the upxReaper contract, we will have to update
// the contract after, with the upxReaper address (or use a middleman address)
// Also: since there may be multiple staking periods we need to think about the future here.
// WE could have an option to set/reset/change the staking period
// We could also make it so during this period, upxReaper essentially determines
// how much per block to provide based on the amount of wUPX/bUPX it holds, since
// the number will change based on taxes AND potential block rewards.
_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) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
/* If burning, burn the full amount.
We should also ensure that upxReaper does not pay taxes when paying out rewards */
if (_isExcluded[sender]) {
_transferFromExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
/* Standard transfer w/ 1% tax to go to farming rewards */
function _transferStandard(address sender, address recipient, uint256 amount) internal virtual {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(amount);
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(tTransferAmount);
_doTax(sender, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
// Transfer without tax: for LPs and upxReaper
function _transferFromExcluded(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);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _doTax(address sender, uint256 tFee) private {
_tFeeTotal = _tFeeTotal.add(tFee);
address recipient = _taxWallet;
_balances[recipient] = _balances[recipient].add(tFee);
emit Transfer(sender, recipient, tFee);
}
// Excluded?
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
// Display total fees collected
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
// Display address of the tax wallet
function taxWallet() public view returns (address) {
return _taxWallet;
}
/** @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);
}
/* multiMint mints to multiple addresses to reduce TX's in bridge queue */
function _multiMint(address[] memory account, uint256[] memory amount) internal virtual {
require(account.length == amount.length, "Account length does not match amount");
uint256 length = account.length;
for (uint256 addy = 0; addy < length; ++addy) {
_mint(account[addy], amount[addy]);
}
}
/**
* Any user may burn their tokens with a note.
* When using with the bridge, the note is tracked
* for automagic swaps back to UPX coin.
*/
function burnSwap(uint256 _value, string memory _note) public {
_burn(msg.sender, _value, _note);
}
/**
* @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, string memory _note) 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 Burn(account, amount, _note);
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 Changes custodial tax wallet of the contract to a new account (`newTaxWallet`).
* Can only be called by the current owner.
*/
function _changeTaxWallet(address newTaxWallet) internal virtual {
require(newTaxWallet != address(0), "Ownable: new tax wallet is the zero address");
emit TaxWalletTransferred(_taxWallet, newTaxWallet);
_taxWallet = newTaxWallet;
}
// For excluding LPs and upxReaper from Taxes on outgoing TXs
function _excludeAccount(address account) internal virtual {
_isExcluded[account] = true;
emit ExcludedAccount(account);
}
function _includeAccount(address account) internal virtual {
require(_isExcluded[account], "Account is already included");
_isExcluded[account] = false;
emit IncludedAccount(account);
}
/**
* @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 { }
}
// Wrapped uPlexa Token
contract WrappeduPlexa is ERC20("Wrapped uPlexa", "wUPX"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner/bridge
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
/// @notice Creates `_amount` token to `_to`. Note: these are arrays.
function multiMint(address[] memory _to, uint256[] memory _amount) public onlyOwner {
_multiMint(_to, _amount);
}
/// @notice Changes `_taxWallet` address to `_to`. Must only be called by the owner/bridge
function changeTaxWallet(address _to) public onlyOwner {
_changeTaxWallet(_to);
}
// Exclude account from paying taxes on sends (such as upxReaper and LPs)
function excludeAccount(address _account) public onlyOwner {
_excludeAccount(_account);
}
// Revert an exclude
function includeAccount(address _account) public onlyOwner {
_includeAccount(_account);
}
}
contract upxReaper is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of wUPX
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accUPXPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accUPXPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. wUPX to distribute per block.
uint256 lastRewardBlock; // Last block number that wUPX distribution occurs.
uint256 accUPXPerShare; // Accumulated wUPX per share, times 1e12. See below.
}
// The wUPX TOKEN!
WrappeduPlexa public wupx;
// Block number when wUPX farming period ends.
uint256 public endBlock;
// wUPX Tokens per block.
uint256 public upxPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Map out LP addresses so we cannot add them twice.
mapping (address => bool) private _isAdded;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when wUPX mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event NewStakingPeriod(uint256 indexed startHeight, uint256 indexed endHeight, uint256 indexed reward);
constructor(
WrappeduPlexa _wupx,
uint256 _startBlock,
uint256 _endBlock,
uint256 _upxPerBlock
) public {
wupx = _wupx;
endBlock = _endBlock;
startBlock = _startBlock;
upxPerBlock = _upxPerBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// For adding a new staking period once the old one has expired.
// Probably a good idea to update all pools prior to new period.
// We will not need to adjust for start date, rather only endBlock will matter
// after adding a new period.
function newPeriod(uint256 _startHeight, uint256 _endHeight, uint256 _reward, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
startBlock = _startHeight;
endBlock = _endHeight;
upxPerBlock = _reward;
emit NewStakingPeriod(_startHeight, _endHeight, _reward);
}
// Add a new lp to the pool. Can only be called by the owner.
// LP cannot be added twice and thus cannot break rewards.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
require(!_isAdded[address(_lpToken)], "LP has already been added.");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accUPXPerShare: 0
}));
_isAdded[address(_lpToken)] = true;
}
// Update the given pool's wUPX allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= endBlock) {
return _to.sub(_from);
} else if (_from >= endBlock) {
return 0; // End of rewards.
} else {
// Just in case the last few blocks have not been accounted for yet.
return endBlock.sub(_from);
}
}
// View function to see pending wUPX on frontend.
function pendingUPX(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accUPXPerShare = pool.accUPXPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if(multiplier>0){
uint256 wupxReward = multiplier.mul(upxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accUPXPerShare = accUPXPerShare.add(wupxReward.mul(1e12).div(lpSupply));
}
}
return user.amount.mul(accUPXPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if(multiplier>0){
uint256 wupxReward = multiplier.mul(upxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accUPXPerShare = pool.accUPXPerShare.add(wupxReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
}
// Deposit LP tokens to upxReaper for UPX allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accUPXPerShare).div(1e12).sub(user.rewardDebt);
safeUPXTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accUPXPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from upxReaper.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accUPXPerShare).div(1e12).sub(user.rewardDebt);
safeUPXTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accUPXPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe wupx transfer function, just in case if rounding error causes pool to not have enough wUPX.
function safeUPXTransfer(address _to, uint256 _amount) internal {
uint256 wupxBal = wupx.balanceOf(address(this));
if (_amount > wupxBal) {
wupx.transfer(_to, wupxBal);
} else {
wupx.transfer(_to, _amount);
}
}
}
|
multiMint mints to multiple addresses to reduce TX's in bridge queue /
|
function _multiMint(address[] memory account, uint256[] memory amount) internal virtual {
require(account.length == amount.length, "Account length does not match amount");
uint256 length = account.length;
for (uint256 addy = 0; addy < length; ++addy) {
_mint(account[addy], amount[addy]);
}
}
| 6,678,605
|
pragma solidity ^0.4.24;
/**
* Based on the open source code of PowerH3D, we built our UPower application ecosystem.
* We will inherit the open source spirit of PowerH3D and accept the community review.
* In future, we will launch more creative games to enrich UPower ecosystem.
* Thanks to Just Team!
*/
contract MC2events {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 UPAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 UPAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 UPAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 UPAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is MC2events {}
contract MC2long is modularLong {
using SafeMath for *;
using NameFilter for string;
using MC2KeysCalcLong for uint256;
otherMC2 private otherMC2_;
DiviesInterface constant private Divies = DiviesInterface(0x33F43Dd20855979f617a983dDBcb4C1C0FA89B2e);
JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0x609e4bb4deE240485Fa546D2bEA2EfAE583E72aC);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xfEc91702792A45070AD7F4Bb07Ed678B863Bc722);
MC2SettingInterface constant private extSetting = MC2SettingInterface(0x8371c74F75274602Bdc4efaC209DA5B15E262E4e);
string constant public name = "MC2 COSMOS";
string constant public symbol = "MC2";
uint256 private rndExtra_ = extSetting.getLongExtra(); // length of the very first ICO
uint256 private rndGap_ = extSetting.getLongGap(); // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 30 minutes; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 60 minutes; // max length a round timer can be
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => MC2datasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => MC2datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => MC2datasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => MC2datasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => MC2datasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (MC2, UP) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = MC2datasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = MC2datasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = MC2datasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = MC2datasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (MC2, UP)
potSplit_[0] = MC2datasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = MC2datasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = MC2datasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = MC2datasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
}
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
MC2datasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
MC2datasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
MC2datasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
MC2datasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
MC2datasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
MC2datasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
MC2datasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
MC2datasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit MC2events.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.UPAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit MC2events.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit MC2events.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit MC2events.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit MC2events.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, MC2datasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit MC2events.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.UPAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, MC2datasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit MC2events.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.UPAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, MC2datasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(MC2datasets.EventReturns memory _eventData_)
private
returns (MC2datasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, MC2datasets.EventReturns memory _eventData_)
private
returns (MC2datasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(MC2datasets.EventReturns memory _eventData_)
private
returns (MC2datasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// up share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _up = (_pot.mul(potSplit_[_winTID].up)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_up);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of MC2 with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_up = _up.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for up to divies
if (_up > 0)
Divies.deposit.value(_up)();
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.UPAmount = _up;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and up
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, MC2datasets.EventReturns memory _eventData_)
private
returns(MC2datasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _up;
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of MC2 with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_up = _com;
_com = 0;
}
// pay 1% out to MC2 short
uint256 _long = _eth / 100;
otherMC2_.potSwap.value(_long)();
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit MC2events.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_up = _aff;
}
// pay out up
_up = _up.add((_eth.mul(fees_[_team].up)) / (100));
if (_up > 0)
{
// deposit to divies contract
Divies.deposit.value(_up)();
// set up event data
_eventData_.UPAmount = _up.add(_eventData_.UPAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit MC2events.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, MC2datasets.EventReturns memory _eventData_)
private
returns(MC2datasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + up share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].up)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, MC2datasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit MC2events.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.UPAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0x1d85A7C26952d4a7D940573eaE73f44D0D6Fa76D ||
msg.sender == 0x5724fc4Abb369C6F2339F784E5b42189f3d30180 ||
msg.sender == 0x6Be04d4ef139eE9fd08A32FdBFb7A532Fe9eD53F ||
msg.sender == 0x53E3E6444C416e2A981644706A8E5E9C13511cf7 ||
msg.sender == 0xEeF4f752D105fEaCB288bB7071F619A2E90a34aC,
"only team just can activate"
);
// make sure that its been linked.
require(address(otherMC2_) != address(0), "must link to other MC2 first");
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherMC2)
public
{
// only team just can activate
require(
msg.sender == 0x1d85A7C26952d4a7D940573eaE73f44D0D6Fa76D ||
msg.sender == 0x5724fc4Abb369C6F2339F784E5b42189f3d30180 ||
msg.sender == 0x6Be04d4ef139eE9fd08A32FdBFb7A532Fe9eD53F ||
msg.sender == 0x53E3E6444C416e2A981644706A8E5E9C13511cf7 ||
msg.sender == 0xEeF4f752D105fEaCB288bB7071F619A2E90a34aC,
"only team just can activate"
);
// make sure that it HASNT yet been linked.
require(address(otherMC2_) == address(0), "silly dev, you already did that");
// set up other fomo3d (fast or long) for pot swap
otherMC2_ = otherMC2(_otherMC2);
}
}
library MC2datasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 UPAmount; // amount distributed to up
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 up; // % of buy in thats paid to up holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 up; // % of pot thats paid to up holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library MC2KeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface otherMC2 {
function potSwap() external payable;
}
interface MC2SettingInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
logic runs whenever a reload order is executed. determines how to handle incoming eth depending on if we are in an active round or not/ setup local rID grab time if round is active get earnings from all vaults and return unused to gen vault because we use a custom safemath library. this will throw if player tried to spend more eth than they have. call core if round is not active and end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event
|
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, MC2datasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit MC2events.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.UPAmount,
_eventData_.genAmount
);
}
}
| 14,361,337
|
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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].
*/
abstract 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 () {
_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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @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 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - 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. 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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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) {
// This method relies on 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;
}
/**
* @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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
} else if (signature.length == 64) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (governor) that can be granted exclusive access to
* specific functions.
*
* By default, the governor account will be the one that deploys the contract. This
* can later be changed with {transferGovernorship}.
*
*/
contract Governed is Context, Initializable {
address public governor;
address private proposedGovernor;
event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor);
/**
* @dev Initializes the contract setting the deployer as the initial governor.
*/
constructor() {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev If inheriting child is using proxy then child contract can use
* _initializeGoverned() function to initialization this contract
*/
function _initializeGoverned() internal initializer {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev Throws if called by any account other than the governor.
*/
modifier onlyGovernor {
require(governor == _msgSender(), "not-the-governor");
_;
}
/**
* @dev Transfers governorship of the contract to a new account (`proposedGovernor`).
* Can only be called by the current owner.
*/
function transferGovernorship(address _proposedGovernor) external onlyGovernor {
require(_proposedGovernor != address(0), "proposed-governor-is-zero");
proposedGovernor = _proposedGovernor;
}
/**
* @dev Allows new governor to accept governorship of the contract.
*/
function acceptGovernorship() external {
require(proposedGovernor == _msgSender(), "not-the-proposed-governor");
emit UpdatedGovernor(governor, proposedGovernor);
governor = proposedGovernor;
proposedGovernor = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier whenPaused() {
require(paused, "not-paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "not-shutdown");
_;
}
/// @dev Pause contract operations, if contract is not paused.
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
/// @dev Unpause contract operations, allow only if contract is paused and not shutdown.
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
/// @dev Shutdown contract operations, if not already shutdown.
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
/// @dev Open contract operations, if contract is in shutdown state
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolAccountant {
function decreaseDebt(address _strategy, uint256 _decreaseBy) external;
function migrateStrategy(address _old, address _new) external;
function reportEarning(
address _strategy,
uint256 _profit,
uint256 _loss,
uint256 _payback
)
external
returns (
uint256 _actualPayback,
uint256 _creditLine,
uint256 _interestFee
);
function reportLoss(address _strategy, uint256 _loss) external;
function availableCreditLimit(address _strategy) external view returns (uint256);
function excessDebt(address _strategy) external view returns (uint256);
function getStrategies() external view returns (address[] memory);
function getWithdrawQueue() external view returns (address[] memory);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function totalDebt() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalDebtRatio() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolRewards {
/// Emitted after reward added
event RewardAdded(uint256 reward);
/// Emitted whenever any user claim rewards
event RewardPaid(address indexed user, uint256 reward);
/// Emitted when reward is ended
event RewardEnded(address indexed dustReceiver, uint256 dust);
// Emitted when pool governor update reward end time
event UpdatedRewardEndTime(uint256 previousRewardEndTime, uint256 newRewardEndTime);
function claimReward(address) external;
function notifyRewardAmount(uint256 rewardAmount, uint256 endTime) external;
function updateRewardEndTime() external;
function updateReward(address) external;
function withdrawRemaining(address _toAddress) external;
function claimable(address) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardForDuration() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/// @title Errors library
library Errors {
string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0
string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0
string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0
string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length
string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee
string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed
string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set
string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep
string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow
string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero
string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS
string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again
string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list
string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list
string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required
string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required
string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool
string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS
string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0
string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// solhint-disable reason-string, no-empty-blocks
///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20
abstract contract PoolERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the decimals of the token. default to 18
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev Returns total supply of the token.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) public view virtual 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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 += amount;
_balances[account] += 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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This 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 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 {}
function _setName(string memory name_) internal {
_name = name_;
}
function _setSymbol(string memory symbol_) internal {
_symbol = symbol_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./PoolERC20.sol";
///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit
// solhint-disable var-name-mixedcase
abstract contract PoolERC20Permit is PoolERC20, IERC20Permit {
bytes32 private constant _EIP712_VERSION = keccak256(bytes("1"));
bytes32 private constant _EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private _CACHED_DOMAIN_SEPARATOR;
bytes32 private _HASHED_NAME;
uint256 private _CACHED_CHAIN_ID;
/**
* @dev See {IERC20Permit-nonces}.
*/
mapping(address => uint256) public override nonces;
/**
* @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`.
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function _initializePermit(string memory name_) internal {
_HASHED_NAME = keccak256(bytes(name_));
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
uint256 _currentNonce = nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline));
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
nonces[owner] = _currentNonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() private view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./PoolERC20Permit.sol";
import "./PoolStorage.sol";
import "./Errors.sol";
import "../Governed.sol";
import "../Pausable.sol";
import "../interfaces/bloq/IAddressList.sol";
import "../interfaces/vesper/IPoolRewards.sol";
/// @title Holding pool share token
// solhint-disable no-empty-blocks
abstract contract PoolShareToken is Initializable, PoolStorageV1, PoolERC20Permit, Governed, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant MAX_BPS = 10_000;
event Deposit(address indexed owner, uint256 shares, uint256 amount);
event Withdraw(address indexed owner, uint256 shares, uint256 amount);
constructor(
string memory _name,
string memory _symbol,
address _token
) PoolERC20(_name, _symbol) {
token = IERC20(_token);
}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializePool(
string memory _name,
string memory _symbol,
address _token
) internal initializer {
_setName(_name);
_setSymbol(_symbol);
_initializePermit(_name);
token = IERC20(_token);
// Assuming token supports 18 or less decimals
uint256 _decimals = IERC20Metadata(_token).decimals();
decimalConversionFactor = _decimals == 18 ? 1 : 10**(18 - _decimals);
}
/**
* @notice Deposit ERC20 tokens and receive pool shares depending on the current share price.
* @param _amount ERC20 token amount.
*/
function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused {
_deposit(_amount);
}
/**
* @notice Deposit ERC20 tokens with permit aka gasless approval.
* @param _amount ERC20 token amount.
* @param _deadline The time at which signature will expire
* @param _v The recovery byte of the signature
* @param _r Half of the ECDSA signature pair
* @param _s Half of the ECDSA signature pair
*/
function depositWithPermit(
uint256 _amount,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external virtual nonReentrant whenNotPaused {
IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s);
_deposit(_amount);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector.
* Burn remaining shares and return collateral.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
_withdraw(_shares);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* @dev Burn shares and return collateral. No withdraw fee will be assessed
* when this function is called. Only some white listed address can call this function.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
require(IAddressList(feeWhitelist).contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS);
_withdrawWithoutFee(_shares);
}
/**
* @notice Transfer tokens to multiple recipient
* @dev Address array and amount array are 1:1 and are in order.
* @param _recipients array of recipient addresses
* @param _amounts array of token amounts
* @return true/false
*/
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool) {
require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH);
for (uint256 i = 0; i < _recipients.length; i++) {
require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED);
}
return true;
}
/**
* @notice Get price per share
* @dev Return value will be in token defined decimals.
*/
function pricePerShare() public view returns (uint256) {
if (totalSupply() == 0 || totalValue() == 0) {
return convertFrom18(1e18);
}
return (totalValue() * 1e18) / totalSupply();
}
/// @dev Convert from 18 decimals to token defined decimals.
function convertFrom18(uint256 _amount) public view virtual returns (uint256) {
return _amount / decimalConversionFactor;
}
/// @dev Returns the token stored in the pool. It will be in token defined decimals.
function tokensHere() public view virtual returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Returns sum of token locked in other contracts and token stored in the pool.
* Default tokensHere. It will be in token defined decimals.
*/
function totalValue() public view virtual returns (uint256);
/**
* @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue
* @param _share Pool share in 18 decimals
*/
function _beforeBurning(uint256 _share) internal virtual returns (uint256) {}
/**
* @dev Hook that is called just after burning tokens.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterBurning(uint256 _amount) internal virtual returns (uint256) {
token.safeTransfer(_msgSender(), _amount);
return _amount;
}
/**
* @dev Hook that is called just before minting new tokens. To be used i.e.
* if the deposited amount is to be transferred from user to this contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _beforeMinting(uint256 _amount) internal virtual {
token.safeTransferFrom(_msgSender(), address(this), _amount);
}
/**
* @dev Hook that is called just after minting new tokens. To be used i.e.
* if the deposited amount is to be transferred to a different contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterMinting(uint256 _amount) internal virtual {}
/// @dev Update pool rewards of sender and receiver during transfer.
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).updateReward(sender);
IPoolRewards(poolRewards).updateReward(recipient);
}
super._transfer(sender, recipient, amount);
}
/**
* @dev Calculate shares to mint based on the current share price and given amount.
* @param _amount Collateral amount in collateral token defined decimals.
* @return share amount in 18 decimal
*/
function _calculateShares(uint256 _amount) internal view returns (uint256) {
require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT);
uint256 _share = ((_amount * 1e18) / pricePerShare());
return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share;
}
/// @notice claim rewards of account
function _claimRewards(address _account) internal {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).claimReward(_account);
}
}
/// @dev Deposit incoming token and mint pool token i.e. shares.
function _deposit(uint256 _amount) internal {
_claimRewards(_msgSender());
uint256 _shares = _calculateShares(_amount);
_beforeMinting(_amount);
_mint(_msgSender(), _shares);
_afterMinting(_amount);
emit Deposit(_msgSender(), _shares, _amount);
}
/// @dev Burns shares and returns the collateral value, after fee, of those.
function _withdraw(uint256 _shares) internal {
if (withdrawFee == 0) {
_withdrawWithoutFee(_shares);
} else {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
uint256 _fee = (_shares * withdrawFee) / MAX_BPS;
uint256 _sharesAfterFee = _shares - _fee;
uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee);
// Recalculate proportional share on actual amount withdrawn
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
// Using convertFrom18() to avoid dust.
// Pool share token is in 18 decimal and collateral token decimal is <=18.
// Anything less than 10**(18-collateralTokenDecimal) is dust.
if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) {
// Recalculate shares to withdraw, fee and shareAfterFee
_shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee);
_fee = _shares - _proportionalShares;
_sharesAfterFee = _proportionalShares;
}
_burn(_msgSender(), _sharesAfterFee);
_transfer(_msgSender(), feeCollector, _fee);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
/// @dev Burns shares and returns the collateral value of those.
function _withdrawWithoutFee(uint256 _shares) internal {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
uint256 _amountWithdrawn = _beforeBurning(_shares);
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) {
_shares = _proportionalShares;
}
_burn(_msgSender(), _shares);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract PoolStorageV1 {
IERC20 public token; // Collateral token
address public poolAccountant; // PoolAccountant address
address public poolRewards; // PoolRewards contract address
address public feeWhitelist; // sol-address-list address which contains whitelisted addresses to withdraw without fee
address public keepers; // sol-address-list address which contains addresses of keepers
address public maintainers; // sol-address-list address which contains addresses of maintainers
address public feeCollector; // Fee collector address
uint256 public withdrawFee; // Withdraw fee for this pool
uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals
bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./VPoolBase.sol";
//solhint-disable no-empty-blocks
contract VPool is VPoolBase {
string public constant VERSION = "3.0.3";
constructor(
string memory _name,
string memory _symbol,
address _token
) VPoolBase(_name, _symbol, _token) {}
function initialize(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant,
address _addressListFactory
) public initializer {
_initializeBase(_name, _symbol, _token, _poolAccountant, _addressListFactory);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./Errors.sol";
import "./PoolShareToken.sol";
import "../interfaces/vesper/IPoolAccountant.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/bloq/IAddressListFactory.sol";
abstract contract VPoolBase is PoolShareToken {
using SafeERC20 for IERC20;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards);
event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee);
constructor(
string memory _name,
string memory _symbol,
address _token // solhint-disable-next-line no-empty-blocks
) PoolShareToken(_name, _symbol, _token) {}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializeBase(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant,
address _addressListFactory
) internal initializer {
_initializePool(_name, _symbol, _token);
_initializeGoverned();
_initializeAddressLists(_addressListFactory);
poolAccountant = _poolAccountant;
}
/**
* @notice Create feeWhitelist, keeper and maintainer list
* @dev Add caller into the keeper and maintainer list
* @dev This function will be used as part of initializer
* @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param
* ethereum - 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3
* polygon - 0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291
*/
function _initializeAddressLists(address _addressListFactory) internal {
require(address(keepers) == address(0), Errors.ALREADY_INITIALIZED);
IAddressListFactory _factory = IAddressListFactory(_addressListFactory);
feeWhitelist = _factory.createList();
keepers = _factory.createList();
maintainers = _factory.createList();
// List creator can do job of keeper and maintainer.
IAddressList(keepers).add(_msgSender());
IAddressList(maintainers).add(_msgSender());
}
modifier onlyKeeper() {
require(IAddressList(keepers).contains(_msgSender()), "not-a-keeper");
_;
}
modifier onlyMaintainer() {
require(IAddressList(maintainers).contains(_msgSender()), "not-a-maintainer");
_;
}
////////////////////////////// Only Governor //////////////////////////////
/**
* @notice Migrate existing strategy to new strategy.
* @dev Migrating strategy aka old and new strategy should be of same type.
* @param _old Address of strategy being migrated
* @param _new Address of new strategy
*/
function migrateStrategy(address _old, address _new) external onlyGovernor {
require(
IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this),
Errors.INVALID_STRATEGY
);
IPoolAccountant(poolAccountant).migrateStrategy(_old, _new);
IStrategy(_old).migrate(_new);
}
/**
* @notice Update fee collector address for this pool
* @param _newFeeCollector new fee collector address
*/
function updateFeeCollector(address _newFeeCollector) external onlyGovernor {
require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedFeeCollector(feeCollector, _newFeeCollector);
feeCollector = _newFeeCollector;
}
/**
* @notice Update pool rewards address for this pool
* @param _newPoolRewards new pool rewards address
*/
function updatePoolRewards(address _newPoolRewards) external onlyGovernor {
require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedPoolRewards(poolRewards, _newPoolRewards);
poolRewards = _newPoolRewards;
}
/**
* @notice Update withdraw fee for this pool
* @dev Format: 1500 = 15% fee, 100 = 1%
* @param _newWithdrawFee new withdraw fee
*/
function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor {
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED);
emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee);
withdrawFee = _newWithdrawFee;
}
///////////////////////////// Only Keeper ///////////////////////////////
function pause() external onlyKeeper {
_pause();
}
function unpause() external onlyKeeper {
_unpause();
}
function shutdown() external onlyKeeper {
_shutdown();
}
function open() external onlyKeeper {
_open();
}
/**
* @notice Add given address in provided address list.
* @dev Use it to add keeper in keepers list and to add address in feeWhitelist
* @param _listToUpdate address of AddressList contract.
* @param _addressToAdd address which we want to add in AddressList.
*/
function addInList(address _listToUpdate, address _addressToAdd) external onlyKeeper {
require(IAddressList(_listToUpdate).add(_addressToAdd), Errors.ADD_IN_LIST_FAILED);
}
/**
* @notice Remove given address from provided address list.
* @dev Use it to remove keeper from keepers list and to remove address from feeWhitelist
* @param _listToUpdate address of AddressList contract.
* @param _addressToRemove address which we want to remove from AddressList.
*/
function removeFromList(address _listToUpdate, address _addressToRemove) external onlyKeeper {
require(IAddressList(_listToUpdate).remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED);
}
///////////////////////////////////////////////////////////////////////////
/**
* @dev Strategy call this in regular interval.
* @param _profit yield generated by strategy. Strategy get performance fee on this amount
* @param _loss Reduce debt ,also reduce debtRatio, increase loss in record.
* @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount.
* when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately.
*/
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external {
(uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) =
IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback);
uint256 _totalPayback = _profit + _actualPayback;
// After payback, if strategy has credit line available then send more fund to strategy
// If payback is more than available credit line then get fund from strategy
if (_totalPayback < _creditLine) {
token.safeTransfer(_msgSender(), _creditLine - _totalPayback);
} else if (_totalPayback > _creditLine) {
token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine);
}
// Mint interest fee worth shares at strategy address
if (_interestFee != 0) {
_mint(_msgSender(), _calculateShares(_interestFee));
}
}
/**
* @notice Report loss outside of rebalance activity.
* @dev Some strategies pay deposit fee thus realizing loss at deposit.
* For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool.
* Strategy may want report this loss instead of waiting for next rebalance.
* @param _loss Loss that strategy want to report
*/
function reportLoss(uint256 _loss) external {
IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss);
}
/**
* @dev Transfer given ERC20 token to feeCollector
* @param _fromToken Token address to sweep
*/
function sweepERC20(address _fromToken) external virtual onlyKeeper {
require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP);
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this)));
}
/**
* @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool
* @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy.
* credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance)
* when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool
* @param _strategy Strategy address
*/
function availableCreditLimit(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy);
}
/**
* @notice Debt above current debt limit
* @param _strategy Address of strategy
*/
function excessDebt(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).excessDebt(_strategy);
}
function getStrategies() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getStrategies();
}
function getWithdrawQueue() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getWithdrawQueue();
}
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
)
{
return IPoolAccountant(poolAccountant).strategy(_strategy);
}
/// @notice Get total debt of pool
function totalDebt() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt();
}
/**
* @notice Get total debt of given strategy
* @param _strategy Strategy address
*/
function totalDebtOf(address _strategy) public view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtOf(_strategy);
}
/// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool
function totalDebtRatio() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtRatio();
}
/// @dev Returns total value of vesper pool, in terms of collateral token
function totalValue() public view override returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt() + tokensHere();
}
function _withdrawCollateral(uint256 _amount) internal virtual {
// Withdraw amount from queue
uint256 _debt;
uint256 _balanceAfter;
uint256 _balanceBefore;
uint256 _amountWithdrawn;
uint256 _amountNeeded = _amount;
uint256 _totalAmountWithdrawn;
address[] memory _withdrawQueue = getWithdrawQueue();
for (uint256 i; i < _withdrawQueue.length; i++) {
_debt = totalDebtOf(_withdrawQueue[i]);
if (_debt == 0) {
continue;
}
if (_amountNeeded > _debt) {
// Should not withdraw more than current debt of strategy.
_amountNeeded = _debt;
}
_balanceBefore = tokensHere();
//solhint-disable no-empty-blocks
try IStrategy(_withdrawQueue[i]).withdraw(_amountNeeded) {} catch {
continue;
}
_balanceAfter = tokensHere();
_amountWithdrawn = _balanceAfter - _balanceBefore;
// Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded
IPoolAccountant(poolAccountant).decreaseDebt(_withdrawQueue[i], _amountWithdrawn);
_totalAmountWithdrawn += _amountWithdrawn;
if (_totalAmountWithdrawn >= _amount) {
// withdraw done
break;
}
_amountNeeded = _amount - _totalAmountWithdrawn;
}
}
/**
* @dev Before burning hook.
* withdraw amount from strategies
*/
function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) {
uint256 _amount = (_share * pricePerShare()) / 1e18;
uint256 _balanceNow = tokensHere();
if (_amount > _balanceNow) {
_withdrawCollateral(_amount - _balanceNow);
_balanceNow = tokensHere();
}
actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount;
}
}
|
Get total debt ratio. Total debt ratio helps us keep buffer in pool
|
function totalDebtRatio() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtRatio();
}
| 166,389
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.6.2 https://hardhat.org
// File contracts/Curve/IStableSwap3Pool.sol
interface IStableSwap3Pool {
// Deployment
function __init__(address _owner, address[3] memory _coins, address _pool_token, uint256 _A, uint256 _fee, uint256 _admin_fee) external;
// ERC20 Standard
function decimals() external view returns (uint);
function transfer(address _to, uint _value) external returns (uint256);
function transferFrom(address _from, address _to, uint _value) external returns (bool);
function approve(address _spender, uint _value) external returns (bool);
function totalSupply() external view returns (uint);
function mint(address _to, uint256 _value) external returns (bool);
function burnFrom(address _to, uint256 _value) external returns (bool);
function balanceOf(address _owner) external view returns (uint256);
// 3Pool
function A() external view returns (uint);
function get_virtual_price() external view returns (uint);
function calc_token_amount(uint[3] memory amounts, bool deposit) external view returns (uint);
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external;
function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256);
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;
function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external;
function remove_liquidity_imbalance(uint256[3] memory amounts, uint256 max_burn_amount) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;
// Admin functions
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external;
function apply_new_fee() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function admin_balances(uint256 i) external returns (uint256);
function withdraw_admin_fees() external;
function donate_admin_fees() external;
function kill_me() external;
function unkill_me() external;
}
// File contracts/Curve/IMetaImplementationUSD.sol
interface IMetaImplementationUSD {
// Deployment
function __init__() external;
function initialize(string memory _name, string memory _symbol, address _coin, uint _decimals, uint _A, uint _fee, address _admin) external;
// ERC20 Standard
function decimals() external view returns (uint);
function transfer(address _to, uint _value) external returns (uint256);
function transferFrom(address _from, address _to, uint _value) external returns (bool);
function approve(address _spender, uint _value) external returns (bool);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
// StableSwap Functionality
function get_previous_balances() external view returns (uint[2] memory);
function get_twap_balances(uint[2] memory _first_balances, uint[2] memory _last_balances, uint _time_elapsed) external view returns (uint[2] memory);
function get_price_cumulative_last() external view returns (uint[2] memory);
function admin_fee() external view returns (uint);
function A() external view returns (uint);
function A_precise() external view returns (uint);
function get_virtual_price() external view returns (uint);
function calc_token_amount(uint[2] memory _amounts, bool _is_deposit) external view returns (uint);
function calc_token_amount(uint[2] memory _amounts, bool _is_deposit, bool _previous) external view returns (uint);
function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount) external returns (uint);
function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount, address _receiver) external returns (uint);
function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
function get_dy(int128 i, int128 j, uint256 dx, uint256[2] memory _balances) external view returns (uint256);
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256);
function get_dy_underlying(int128 i, int128 j, uint256 dx, uint256[2] memory _balances) external view returns (uint256);
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver) external returns (uint256);
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver) external returns (uint256);
function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts) external returns (uint256[2] memory);
function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts, address _receiver) external returns (uint256[2] memory);
function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount) external returns (uint256);
function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount, address _receiver) external returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i, bool _previous) external view returns (uint256);
function remove_liquidity_one_coin(uint256 _burn_amount, int128 i, uint256 _min_received) external returns (uint256);
function remove_liquidity_one_coin(uint256 _burn_amount, int128 i, uint256 _min_received, address _receiver) external returns (uint256);
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function admin_balances(uint256 i) external view returns (uint256);
function withdraw_admin_fees() external;
}
// File contracts/Misc_AMOs/morganle/ITC.sol
pragma experimental ABIEncoderV2;
interface ITC {
function CONTRACT_ADMIN_ROLE() external view returns(bytes32);
function SCALE_FACTOR() external view returns(uint256);
function core() external view returns(address);
function deposit(uint256 pid, uint256 amount, uint64 lockLength) external;
function depositInfo(uint256, address, uint256) external view returns(uint256 amount, uint128 unlockBlock, uint128 multiplier);
function emergencyWithdraw(uint256 pid, address to) external;
function getTotalStakedInPool(uint256 pid, address user) external view returns(uint256);
function governorAddPoolMultiplier(uint256 _pid, uint64 lockLength, uint64 newRewardsMultiplier) external;
function harvest(uint256 pid, address to) external;
function isContractAdmin(address _admin) external view returns(bool);
function lockPool(uint256 _pid) external;
function numPools() external view returns(uint256);
function openUserDeposits(uint256 pid, address user) external view returns(uint256);
function pause() external;
function paused() external view returns(bool);
function pendingRewards(uint256 _pid, address _user) external view returns(uint256);
function resetRewards(uint256 _pid) external;
function rewardMultipliers(uint256, uint128) external view returns(uint128);
function rewarder(uint256) external view returns(address);
function set(uint256 _pid, uint120 _allocPoint, address _rewarder, bool overwrite) external;
function setContractAdminRole(bytes32 newContractAdminRole) external;
function setCore(address newCore) external;
function stakedToken(uint256) external view returns(address);
function totalAllocPoint() external view returns(uint256);
function unlockPool(uint256 _pid) external;
function unpause() external;
function updateBlockReward(uint256 newBlockReward) external;
function updatePool(uint256 pid) external;
function userInfo(uint256, address) external view returns(int256 rewardDebt, uint256 virtualAmount);
function withdrawAllAndHarvest(uint256 pid, address to) external;
function withdrawFromDeposit(uint256 pid, uint256 amount, address to, uint256 index) external;
}
// File contracts/Uniswap/TransferHelper.sol
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/Common/Context.sol
/*
* @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 payable(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 contracts/Math/SafeMath.sol
/**
* @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/ERC20/IERC20.sol
/**
* @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/Utils/Address.sol
/**
* @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) {
// This method relies on 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;
}
/**
* @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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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 contracts/ERC20/ERC20.sol
/**
* @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 {ERC20Mintable}.
*
* 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;
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.approve(address spender, uint256 amount)
*/
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/Frax/IFrax.sol
interface IFrax {
function COLLATERAL_RATIO_PAUSER() external view returns (bytes32);
function DEFAULT_ADMIN_ADDRESS() external view returns (address);
function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
function addPool(address pool_address ) external;
function allowance(address owner, address spender ) external view returns (uint256);
function approve(address spender, uint256 amount ) external returns (bool);
function balanceOf(address account ) external view returns (uint256);
function burn(uint256 amount ) external;
function burnFrom(address account, uint256 amount ) external;
function collateral_ratio_paused() external view returns (bool);
function controller_address() external view returns (address);
function creator_address() external view returns (address);
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool);
function eth_usd_consumer_address() external view returns (address);
function eth_usd_price() external view returns (uint256);
function frax_eth_oracle_address() external view returns (address);
function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256);
function frax_pools(address ) external view returns (bool);
function frax_pools_array(uint256 ) external view returns (address);
function frax_price() external view returns (uint256);
function frax_step() external view returns (uint256);
function fxs_address() external view returns (address);
function fxs_eth_oracle_address() external view returns (address);
function fxs_price() external view returns (uint256);
function genesis_supply() external view returns (uint256);
function getRoleAdmin(bytes32 role ) external view returns (bytes32);
function getRoleMember(bytes32 role, uint256 index ) external view returns (address);
function getRoleMemberCount(bytes32 role ) external view returns (uint256);
function globalCollateralValue() external view returns (uint256);
function global_collateral_ratio() external view returns (uint256);
function grantRole(bytes32 role, address account ) external;
function hasRole(bytes32 role, address account ) external view returns (bool);
function increaseAllowance(address spender, uint256 addedValue ) external returns (bool);
function last_call_time() external view returns (uint256);
function minting_fee() external view returns (uint256);
function name() external view returns (string memory);
function owner_address() external view returns (address);
function pool_burn_from(address b_address, uint256 b_amount ) external;
function pool_mint(address m_address, uint256 m_amount ) external;
function price_band() external view returns (uint256);
function price_target() external view returns (uint256);
function redemption_fee() external view returns (uint256);
function refreshCollateralRatio() external;
function refresh_cooldown() external view returns (uint256);
function removePool(address pool_address ) external;
function renounceRole(bytes32 role, address account ) external;
function revokeRole(bytes32 role, address account ) external;
function setController(address _controller_address ) external;
function setETHUSDOracle(address _eth_usd_consumer_address ) external;
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external;
function setFXSAddress(address _fxs_address ) external;
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external;
function setFraxStep(uint256 _new_step ) external;
function setMintingFee(uint256 min_fee ) external;
function setOwner(address _owner_address ) external;
function setPriceBand(uint256 _price_band ) external;
function setPriceTarget(uint256 _new_price_target ) external;
function setRedemptionFee(uint256 red_fee ) external;
function setRefreshCooldown(uint256 _new_cooldown ) external;
function setTimelock(address new_timelock ) external;
function symbol() external view returns (string memory);
function timelock_address() external view returns (address);
function toggleCollateralRatio() external;
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount ) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool);
function weth_address() external view returns (address);
}
// File contracts/Frax/IFraxAMOMinter.sol
interface IFraxAMOMinter {
function FRAX() external view returns(address);
function FXS() external view returns(address);
function acceptOwnership() external;
function addAMO(address amo_address, bool sync_too) external;
function allAMOAddresses() external view returns(address[] memory);
function allAMOsLength() external view returns(uint256);
function amoProfit(address amo_address) external view returns(int256);
function amos(address) external view returns(bool);
function amos_array(uint256) external view returns(address);
function burnFXS(uint256 amount) external;
function burnFraxFromAMO(uint256 frax_amount) external;
function burnFxsFromAMO(uint256 fxs_amount) external;
function col_idx() external view returns(uint256);
function collatDollarBalance() external view returns(uint256);
function collatDollarBalanceStored() external view returns(uint256);
function collat_borrow_cap() external view returns(int256);
function collat_borrowed_balances(address) external view returns(int256);
function collat_borrowed_sum() external view returns(int256);
function collateral_address() external view returns(address);
function collateral_token() external view returns(address);
function custodian_address() external view returns(address);
function fraxDollarBalanceStored() external view returns(uint256);
function giveCollatToAMO(address destination_amo, uint256 collat_amount) external;
function min_cr() external view returns(uint256);
function mintFraxForAMO(address destination_amo, uint256 frax_amount) external;
function mint_balances(address) external view returns(int256);
function mint_cap() external view returns(int256);
function mint_sum() external view returns(int256);
function missing_decimals() external view returns(uint256);
function nominateNewOwner(address _owner) external;
function nominatedOwner() external view returns(address);
function override_collat_balance() external view returns(bool);
function override_collat_balance_amount() external view returns(uint256);
function owner() external view returns(address);
function pool() external view returns(address);
function receiveCollatFromAMO(uint256 usdc_amount) external;
function recoverERC20(address tokenAddress, uint256 tokenAmount) external;
function removeAMO(address amo_address, bool sync_too) external;
function setCustodian(address _custodian_address) external;
function setFraxPool(address _pool_address) external;
function setMinimumCollateralRatio(uint256 _min_cr) external;
function setMintCap(uint256 _mint_cap) external;
function setOverrideCollatBalance(bool _state, uint256 _balance) external;
function setTimelock(address new_timelock) external;
function syncDollarBalances() external;
function timelock_address() external view returns(address);
function unspentProfitGlobal() external view returns(int256);
}
// File contracts/Proxy/Initializable.sol
// solhint-disable-next-line compiler-version
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File contracts/Staking/Owned.sol
// https://docs.synthetix.io/contracts/Owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/Misc_AMOs/CurveMetapoolLockerAMO.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ====================== CurveMetapoolLockerAMO ======================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Dennis: github.com/denett
contract CurveMetapoolLockerAMO is Owned {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
IMetaImplementationUSD private metapool_token;
IStableSwap3Pool private three_pool;
ITC private tc;
ERC20 private three_pool_erc20;
IFrax private FRAX;
ERC20 private collateral_token;
IFraxAMOMinter private amo_minter;
address private collateral_token_address;
address private reward_token_address;
address private metapool_token_address;
address private tc_address;
uint256 private immutable tc_pid = 1;
address public timelock_address;
address public custodian_address;
// Number of decimals under 18, for collateral token
uint256 private missing_decimals;
// Precision related
uint256 private PRICE_PRECISION;
// Min ratio of collat <-> 3crv conversions via add_liquidity / remove_liquidity; 1e6
uint256 public liq_slippage_3crv;
// Min ratio of (FRAX + 3CRV) <-> FRAX3CRV-f-2 metapool conversions via add_liquidity / remove_liquidity; 1e6
uint256 public slippage_metapool;
// Convergence window
uint256 public convergence_window; // 0.1 cent
// Default will use global_collateral_ratio()
bool public custom_floor;
uint256 public frax_floor;
// Discount
bool public set_discount;
uint256 public discount_rate;
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner_address,
address _amo_minter_address
) Owned(_owner_address) {
owner = _owner_address;
FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e);
collateral_token = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
reward_token_address = 0xc7283b66Eb1EB5FB86327f08e1B5816b0720212B;
missing_decimals = uint(18).sub(collateral_token.decimals());
amo_minter = IFraxAMOMinter(_amo_minter_address);
metapool_token_address = 0x06cb22615BA53E60D67Bf6C341a0fD5E718E1655;
metapool_token = IMetaImplementationUSD(metapool_token_address);
three_pool = IStableSwap3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
three_pool_erc20 = ERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
tc_address = 0x9e1076cC0d19F9B0b8019F384B0a29E48Ee46f7f;
tc = ITC(tc_address);
// Other variable initializations
PRICE_PRECISION = 1e6;
liq_slippage_3crv = 800000;
slippage_metapool = 950000;
convergence_window = 1e15;
custom_floor = false;
set_discount = false;
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyByMinter() {
require(msg.sender == address(amo_minter), "Not minter");
_;
}
/* ========== VIEWS ========== */
function showAllocations() public view returns (uint256[6] memory return_arr) {
// ------------LP Balance------------
// Free LP
uint256 lp_free = metapool_token.balanceOf(address(this));
uint256 lp_total_val = (lp_free * metapool_token.get_virtual_price()) / 1e18;
// Staked in the vault
uint256 lp_value_in_vault = usdValueInVault();
lp_total_val += lp_value_in_vault;
// ------------Collateral Balance------------
// Free Collateral
uint256 free_collateral = collateral_token.balanceOf(address(this));
// Free Collateral, in E18
uint256 free_collateral_E18 = free_collateral * (10 ** missing_decimals);
// ------------Total Balances------------
// Total USD value
uint256 total_value_E18 = free_collateral_E18 + lp_total_val;
return [
lp_free, // [0] Free LP
lp_value_in_vault, // [1] Staked LP in the vault
lp_total_val, // [2] Free + Staked LP
free_collateral, // [3] Free Collateral
free_collateral_E18, // [4] Free Collateral, in E18
total_value_E18 // [5] Total USD value
];
}
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
// Get the allocations
uint256[6] memory allocations = showAllocations();
frax_val_e18 = allocations[5];
collat_val_e18 = (allocations[5] * FRAX.global_collateral_ratio()) / PRICE_PRECISION;
}
// Amount of FRAX3CRV deposited in the vault contract
function stakedBalance() public view returns (uint256) {
return tc.getTotalStakedInPool(tc_pid, address(this));
}
function usdValueInVault() public view returns (uint256) {
uint256 vaultBalance = stakedBalance();
return (vaultBalance * metapool_token.get_virtual_price()) / 1e18;
}
// Backwards compatibility
function mintedBalance() public view returns (int256) {
return amo_minter.mint_balances(address(this));
}
/* ========== RESTRICTED FUNCTIONS ========== */
function metapoolDeposit(uint256 _collateral_amount) external onlyByOwnGov returns (uint256 metapool_LP_received) {
uint256 threeCRV_received = 0;
// Approve the collateral to be added to 3pool
collateral_token.approve(address(three_pool), _collateral_amount);
// Convert collateral into 3pool
uint256[3] memory three_pool_collaterals;
three_pool_collaterals[1] = _collateral_amount;
uint256 min_3pool_out = (_collateral_amount * (10 ** missing_decimals)).mul(liq_slippage_3crv).div(PRICE_PRECISION);
three_pool.add_liquidity(three_pool_collaterals, min_3pool_out);
// Approve the 3pool for the metapool
threeCRV_received = three_pool_erc20.balanceOf(address(this));
// WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time
// May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85
three_pool_erc20.approve(metapool_token_address, 0);
three_pool_erc20.approve(metapool_token_address, threeCRV_received);
// Add the FRAX and the collateral to the metapool
uint256 min_lp_out = (threeCRV_received * slippage_metapool) / PRICE_PRECISION;
metapool_LP_received = metapool_token.add_liquidity([0, threeCRV_received], min_lp_out);
return metapool_LP_received;
}
function metapoolWithdraw3pool(uint256 metapool_lp_in) public onlyByOwnGov {
// Withdraw 3pool from the metapool
uint256 min_3pool_out = metapool_lp_in.mul(slippage_metapool).div(PRICE_PRECISION);
metapool_token.remove_liquidity_one_coin(metapool_lp_in, 1, min_3pool_out);
}
function three_pool_to_collateral(uint256 _3pool_in) public onlyByOwnGov {
// Convert the 3pool into the collateral
// WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time
// May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85
three_pool_erc20.approve(address(three_pool), 0);
three_pool_erc20.approve(address(three_pool), _3pool_in);
uint256 min_collat_out = _3pool_in.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals));
three_pool.remove_liquidity_one_coin(_3pool_in, 1, min_collat_out);
}
function metapoolWithdrawAndConvert3pool(uint256 metapool_lp_in) external onlyByOwnGov {
metapoolWithdraw3pool(metapool_lp_in);
three_pool_to_collateral(three_pool_erc20.balanceOf(address(this)));
}
/* ========== Main Functions ========== */
// Deposit Metapool LP tokens into the vault
function depositToVault(uint256 metapool_lp_in, uint64 lock_length) external onlyByOwnGovCust {
// Approve the metapool LP tokens for the vault contract
metapool_token.approve(tc_address, metapool_lp_in);
// Deposit the metapool LP into the vault contract
tc.deposit(tc_pid, metapool_lp_in, lock_length);
}
// Withdraw a specific Metapool LP deposit from the vault back to this contract
function withdrawFromVault(uint256 metapool_lp_out, uint256 deposit_idx) external onlyByOwnGovCust {
tc.withdrawFromDeposit(tc_pid, metapool_lp_out, address(this), deposit_idx);
}
// Withdraw all Metapool LP from the vault back to this contract
function withdrawAllAndHarvest() external onlyByOwnGovCust {
tc.withdrawAllAndHarvest(tc_pid, address(this));
}
/* ========== Rewards ========== */
// Collect rewards
function harvest() external onlyByOwnGovCust {
tc.harvest(tc_pid, address(this));
}
function withdrawRewards() external onlyByOwnGovCust {
// Withdraw CRV
TransferHelper.safeTransfer(0xD533a949740bb3306d119CC777fa900bA034cd52, msg.sender, ERC20(0xD533a949740bb3306d119CC777fa900bA034cd52).balanceOf(address(this)));
// Withdraw the reward tokens
TransferHelper.safeTransfer(reward_token_address, msg.sender, ERC20(reward_token_address).balanceOf(address(this)));
}
/* ========== Burns and givebacks ========== */
// Give USDC profits back. Goes through the minter
function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust {
collateral_token.approve(address(amo_minter), collat_amount);
amo_minter.receiveCollatFromAMO(collat_amount);
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setAMOMinter(address _amo_minter_address) external onlyByOwnGov {
amo_minter = IFraxAMOMinter(_amo_minter_address);
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
// Make sure the new addresses are not address(0)
require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock");
}
function setConvergenceWindow(uint256 _window) external onlyByOwnGov {
convergence_window = _window;
}
// in terms of 1e6 (overriding global_collateral_ratio)
function setDiscountRate(bool _state, uint256 _discount_rate) external onlyByOwnGov {
set_discount = _state;
discount_rate = _discount_rate;
}
function setSlippages(uint256 _liq_slippage_3crv, uint256 _slippage_metapool) external onlyByOwnGov {
liq_slippage_3crv = _liq_slippage_3crv;
slippage_metapool = _slippage_metapool;
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount);
}
}
|
Withdraw 3pool from the metapool
|
function metapoolWithdraw3pool(uint256 metapool_lp_in) public onlyByOwnGov {
uint256 min_3pool_out = metapool_lp_in.mul(slippage_metapool).div(PRICE_PRECISION);
metapool_token.remove_liquidity_one_coin(metapool_lp_in, 1, min_3pool_out);
}
| 404,444
|
./full_match/1/0x4c2EeC8C4D8C51152deDc022a39Be3ac3d4BA5C0/sources/FlatFactory.sol
|
Removes a template creator _newTemplateCreator Address of the to be removed creator/
|
function removeTemplateCreator(address _newTemplateCreator)
external
onlyFactoryOwner
{
for (uint256 i = 0; i < templateCreator.length - 1; i++) {
if (templateCreator[i] == _newTemplateCreator) {
templateCreator[i] = templateCreator[i + 1];
}
}
delete templateCreator[templateCreator.length - 1];
}
| 3,017,024
|
pragma solidity >= 0.6.0;
// Interface of the contract we want to interact with.
abstract contract IBounceCallee {
function receiveMoney(uint128 value) public payable virtual;
function receiveValues(uint16 value1, bool value2, uint64 value3) public virtual;
}
// Contract that can handle errors during intercontract communication.
contract BounceCaller {
// State variables:
uint bounceCounter; // Number of onBounce function calls;
// Saved arguments of function calls which were handled with failure.
uint16 invalidValue1;
bool invalidValue2;
uint64 invalidValue3;
uint128 invalidMoneyAmount;
modifier alwaysAccept {
tvm.accept();
_;
}
// Function onBounce is executed on inbound messages with set <bounced> flag.
// This function takes the body of the message as an argument.
onBounce(TvmSlice slice) external {
// Increase the counter.
bounceCounter++;
// Start decoding the message. First 32 bits store the function id.
uint32 functionId = slice.decode(uint32);
// Api function tvm.functionId() allows to calculate function id by function name.
if (functionId == tvm.functionId(IBounceCallee.receiveMoney)) {
//Function decodeFunctionParams() allows to decode function parameters from the slice.
// After decoding we store the arguments of the function in the state variables.
invalidMoneyAmount = slice.decodeFunctionParams(IBounceCallee.receiveMoney);
} else if (functionId == tvm.functionId(IBounceCallee.receiveValues)) {
(invalidValue1, invalidValue2, invalidValue3) =
slice.decodeFunctionParams(IBounceCallee.receiveValues);
}
}
// Function that calls another contract function and attaches some currency to the call.
function sendMoney(address callee, uint128 amount) public payable alwaysAccept {
IBounceCallee(callee).receiveMoney.value(amount)(amount);
}
// Funciton that calls another contract function with arbitrary arguments.
function sendValues(address callee, uint16 value1, bool value2, uint64 value3) public pure
alwaysAccept {
IBounceCallee(callee).receiveValues(value1, value2, value3);
}
// Function to get state variables.
function getData() public view alwaysAccept returns (uint, uint16, bool, uint64, uint128) {
return (bounceCounter, invalidValue1, invalidValue2, invalidValue3, invalidMoneyAmount);
}
}
|
Function that calls another contract function and attaches some currency to the call.
|
function sendMoney(address callee, uint128 amount) public payable alwaysAccept {
IBounceCallee(callee).receiveMoney.value(amount)(amount);
}
| 5,375,995
|
pragma solidity ^0.4.18;
/************************************************** */
/* WhenHub Token Smart Contract */
/* Author: Nik Kalyani nik@whenhub.com */
/* Copyright (c) 2018 CalendarTree, Inc. */
/* https://interface.whenhub.com */
/************************************************** */
contract WHENToken {
using SafeMath for uint256;
mapping(address => uint256) balances; // Token balance for each address
mapping (address => mapping (address => uint256)) internal allowed; // Approval granted to transfer tokens by one address to another address
/* ERC20 fields */
string public name;
string public symbol;
uint public decimals = 18;
string public sign = "₩";
string public logoPng = "https://github.com/WhenHub/WHEN/raw/master/assets/when-token-icon.png";
/* Each registered user on WhenHub Interface Network has a record in this contract */
struct User {
bool isRegistered; // Flag to indicate user was registered
uint256 seedJiffys; // Tracks free tokens granted to user
uint256 interfaceEscrowJiffys; // Tracks escrow tokens used in Interfaces
address referrer; // Tracks who referred this user
}
// IcoBurnAuthorized is used to determine when remaining ICO tokens should be burned
struct IcoBurnAuthorized {
bool contractOwner; // Flag to indicate ContractOwner has authorized
bool platformManager; // Flag to indicate PlatformManager has authorized
bool icoOwner; // Flag to indicate SupportManager has authorized
}
// PurchaseCredit is used to track purchases made by USD when user isn't already registered
struct PurchaseCredit {
uint256 jiffys; // Number of jiffys purchased
uint256 purchaseTimestamp; // Date/time of original purchase
}
mapping(address => PurchaseCredit) purchaseCredits; // Temporary store for USD-purchased tokens
uint private constant ONE_WEEK = 604800;
uint private constant SECONDS_IN_MONTH = 2629743;
uint256 private constant ICO_START_TIMESTAMP = 1521471600; // 3/19/2018 08:00:00 PDT
uint private constant BASIS_POINTS_TO_PERCENTAGE = 10000; // All fees are expressed in basis points. This makes conversion easier
/* Token allocations per published WhenHub token economics */
uint private constant ICO_TOKENS = 350000000; // Tokens available for public purchase
uint private constant PLATFORM_TOKENS = 227500000; // Tokens available for network seeding
uint private constant COMPANY_TOKENS = 262500000; // Tokens available to WhenHub for employees and future expansion
uint private constant PARTNER_TOKENS = 17500000; // Tokens available for WhenHub partner inventives
uint private constant FOUNDATION_TOKENS = 17500000; // Tokens available for WhenHub Foundationn charity
/* Network seeding tokens */
uint constant INCENTIVE_TOKENS = 150000000; // Total pool of seed tokens for incentives
uint constant REFERRAL_TOKENS = 77500000; // Total pool of seed tokens for referral
uint256 private userSignupJiffys = 0; // Number of Jiffys per user who signs up
uint256 private referralSignupJiffys = 0; // Number of Jiffys per user(x2) referrer + referree
uint256 private jiffysMultiplier; // 10 ** decimals
uint256 private incentiveJiffysBalance; // Available balance of Jiffys for incentives
uint256 private referralJiffysBalance; // Available balance of Jiffys for referrals
/* ICO variables */
uint256 private bonus20EndTimestamp = 0; // End of 20% ICO token bonus timestamp
uint256 private bonus10EndTimestamp = 0; // End of 10% ICO token bonus timestamp
uint256 private bonus5EndTimestamp = 0; // End of 5% ICO token bonus timestamp
uint private constant BUYER_REFERRER_BOUNTY = 3; // Referral bounty percentage
IcoBurnAuthorized icoBurnAuthorized = IcoBurnAuthorized(false, false, false);
/* Interface transaction settings */
bool private operational = true; // Blocks all state changes throughout the contract if false
// Change using setOperatingStatus()
uint256 public winNetworkFeeBasisPoints = 0; // Per transaction fee deducted from payment to Expert
// Change using setWinNetworkFeeBasisPoints()
uint256 public weiExchangeRate = 500000000000000; // Exchange rate for 1 WHEN Token in Wei ($0.25/₩)
// Change using setWeiExchangeRate()
uint256 public centsExchangeRate = 25; // Exchange rate for 1 WHEN Token in cents
// Change using setCentsExchangeRate()
/* State variables */
address private contractOwner; // Account used to deploy contract
address private platformManager; // Account used by API for Interface app
address private icoOwner; // Account from which ICO funds are disbursed
address private supportManager; // Account used by support team to reimburse users
address private icoWallet; // Account to which ICO ETH is sent
mapping(address => User) private users; // All registered users
mapping(address => uint256) private vestingEscrows; // Unvested tokens held in escrow
mapping(address => uint256) private authorizedContracts; // Contracts authorized to call this one
address[] private registeredUserLookup; // Lookup table of registered users
/* ERC-20 Contract Events */
event Approval // Fired when an account authorizes another account to spend tokens on its behalf
(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer // Fired when tokens are transferred from one account to another
(
address indexed from,
address indexed to,
uint256 value
);
/* Interface app-specific Events */
event UserRegister // Fired when a new user account (wallet) is registered
(
address indexed user,
uint256 value,
uint256 seedJiffys
);
event UserRefer // Fired when tokens are granted to a user for referring a new user
(
address indexed user,
address indexed referrer,
uint256 value
);
event UserLink // Fired when a previously existing user is linked to an account in the Interface DB
(
address indexed user
);
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational);
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner);
_;
}
/**
* @dev Modifier that requires the "PlatformManager" account to be the function caller
*/
modifier requirePlatformManager()
{
require(isPlatformManager(msg.sender));
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
* @param tokenName ERC-20 token name
* @param tokenSymbol ERC-20 token symbol
* @param platformAccount Account for making calls from Interface API (i.e. PlatformManager)
* @param icoAccount Account that holds ICO tokens (i.e. IcoOwner)
* @param supportAccount Account with limited access to manage Interface user support (i.e. SupportManager)
*
*/
function WHENToken
(
string tokenName,
string tokenSymbol,
address platformAccount,
address icoAccount,
address supportAccount
)
public
{
name = tokenName;
symbol = tokenSymbol;
jiffysMultiplier = 10 ** uint256(decimals); // Multiplier used throughout contract
incentiveJiffysBalance = INCENTIVE_TOKENS.mul(jiffysMultiplier); // Network seeding tokens
referralJiffysBalance = REFERRAL_TOKENS.mul(jiffysMultiplier); // User referral tokens
contractOwner = msg.sender; // Owner of the contract
platformManager = platformAccount; // API account for Interface
icoOwner = icoAccount; // Account with ICO tokens for settling Interface transactions
icoWallet = icoOwner; // Account to which ICO ETH is sent
supportManager = supportAccount; // Support account with limited permissions
// Create user records for accounts
users[contractOwner] = User(true, 0, 0, address(0));
registeredUserLookup.push(contractOwner);
users[platformManager] = User(true, 0, 0, address(0));
registeredUserLookup.push(platformManager);
users[icoOwner] = User(true, 0, 0, address(0));
registeredUserLookup.push(icoOwner);
users[supportManager] = User(true, 0, 0, address(0));
registeredUserLookup.push(supportManager);
}
/**
* @dev Contract constructor
*
* Initialize is to be called immediately after the supporting contracts are deployed.
*
* @param dataContract Address of the deployed InterfaceData contract
* @param appContract Address of the deployed InterfaceApp contract
* @param vestingContract Address of the deployed TokenVesting contract
*
*/
function initialize
(
address dataContract,
address appContract,
address vestingContract
)
external
requireContractOwner
{
require(bonus20EndTimestamp == 0); // Ensures function cannot be called twice
authorizeContract(dataContract); // Authorizes InterfaceData contract to make calls to this contract
authorizeContract(appContract); // Authorizes InterfaceApp contract to make calls to this contract
authorizeContract(vestingContract); // Authorizes TokenVesting contract to make calls to this contract
bonus20EndTimestamp = ICO_START_TIMESTAMP.add(ONE_WEEK);
bonus10EndTimestamp = bonus20EndTimestamp.add(ONE_WEEK);
bonus5EndTimestamp = bonus10EndTimestamp.add(ONE_WEEK);
// ICO tokens are allocated without vesting to ICO account for distribution during sale
balances[icoOwner] = ICO_TOKENS.mul(jiffysMultiplier);
// Platform tokens (a.k.a. network seeding tokens) are allocated without vesting
balances[platformManager] = balances[platformManager].add(PLATFORM_TOKENS.mul(jiffysMultiplier));
// Allocate all other tokens to contract owner without vesting
// These will be disbursed in initialize()
balances[contractOwner] = balances[contractOwner].add((COMPANY_TOKENS + PARTNER_TOKENS + FOUNDATION_TOKENS).mul(jiffysMultiplier));
userSignupJiffys = jiffysMultiplier.mul(500); // Initial signup incentive
referralSignupJiffys = jiffysMultiplier.mul(100); // Initial referral incentive
}
/**
* @dev Token allocations for various accounts
*
* Called from TokenVesting to grant tokens to each account
*
*/
function getTokenAllocations()
external
view
returns(uint256, uint256, uint256)
{
return (COMPANY_TOKENS.mul(jiffysMultiplier), PARTNER_TOKENS.mul(jiffysMultiplier), FOUNDATION_TOKENS.mul(jiffysMultiplier));
}
/********************************************************************************************/
/* ERC20 TOKEN */
/********************************************************************************************/
/**
* @dev Total supply of tokens
*/
function totalSupply()
external
view
returns (uint)
{
uint256 total = ICO_TOKENS.add(PLATFORM_TOKENS).add(COMPANY_TOKENS).add(PARTNER_TOKENS).add(FOUNDATION_TOKENS);
return total.mul(jiffysMultiplier);
}
/**
* @dev Gets the balance of the calling address.
*
* @return An uint256 representing the amount owned by the calling address
*/
function balance()
public
view
returns (uint256)
{
return balanceOf(msg.sender);
}
/**
* @dev Gets the balance of the specified address.
*
* @param owner The address to query the balance of
* @return An uint256 representing the amount owned by the passed address
*/
function balanceOf
(
address owner
)
public
view
returns (uint256)
{
return balances[owner];
}
/**
* @dev Transfers token for a specified address
*
* Constraints are added to ensure that tokens granted for network
* seeding and tokens in escrow are not transferable
*
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A bool indicating if the transfer was successful.
*/
function transfer
(
address to,
uint256 value
)
public
requireIsOperational
returns (bool)
{
require(to != address(0));
require(to != msg.sender);
require(value <= transferableBalanceOf(msg.sender));
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Transfers tokens from one address to another
*
* Constraints are added to ensure that tokens granted for network
* seeding and tokens in escrow are not transferable
*
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
* @return A bool indicating if the transfer was successful.
*/
function transferFrom
(
address from,
address to,
uint256 value
)
public
requireIsOperational
returns (bool)
{
require(from != address(0));
require(value <= allowed[from][msg.sender]);
require(value <= transferableBalanceOf(from));
require(to != address(0));
require(from != to);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
return true;
}
/**
* @dev Checks the amount of tokens that an owner allowed to a spender.
*
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance
(
address owner,
address spender
)
public
view
returns (uint256)
{
return allowed[owner][spender];
}
/**
* @dev Approves the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A bool indicating success (always returns true)
*/
function approve
(
address spender,
uint256 value
)
public
requireIsOperational
returns (bool)
{
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Gets the balance of the specified address less greater of escrow tokens and free signup tokens.
*
* @param account The address to query the the balance of.
* @return An uint256 representing the transferable amount owned by the passed address.
*/
function transferableBalanceOf
(
address account
)
public
view
returns (uint256)
{
require(account != address(0));
if (users[account].isRegistered) {
uint256 restrictedJiffys = users[account].interfaceEscrowJiffys >= users[account].seedJiffys ? users[account].interfaceEscrowJiffys : users[account].seedJiffys;
return balances[account].sub(restrictedJiffys);
}
return balances[account];
}
/**
* @dev Gets the balance of the specified address less escrow tokens
*
* Since seed tokens can be used to pay for Interface transactions
* this balance indicates what the user can afford to spend for such
* "internal" transactions ignoring distinction between paid and signup tokens
*
* @param account The address to query the balance of.
* @return An uint256 representing the spendable amount owned by the passed address.
*/
function spendableBalanceOf
(
address account
)
public
view
returns(uint256)
{
require(account != address(0));
if (users[account].isRegistered) {
return balances[account].sub(users[account].interfaceEscrowJiffys);
}
return balances[account];
}
/********************************************************************************************/
/* WHENHUB INTERFACE */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this
* one will fail
* @return A bool that is the new operational mode
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/**
* @dev Authorizes ICO end and burn of remaining tokens
*
* ContractOwner, PlatformManager and IcoOwner must each call this function
* in any order. The third entity calling the function will cause the
* icoOwner account balance to be reset to 0.
*/
function authorizeIcoBurn()
external
{
require(balances[icoOwner] > 0);
require((msg.sender == contractOwner) || (msg.sender == platformManager) || (msg.sender == icoOwner));
if (msg.sender == contractOwner) {
icoBurnAuthorized.contractOwner = true;
} else if (msg.sender == platformManager) {
icoBurnAuthorized.platformManager = true;
} else if (msg.sender == icoOwner) {
icoBurnAuthorized.icoOwner = true;
}
if (icoBurnAuthorized.contractOwner && icoBurnAuthorized.platformManager && icoBurnAuthorized.icoOwner) {
balances[icoOwner] = 0;
}
}
/**
* @dev Sets fee used in Interface transactions
*
* A network fee is charged for each transaction represented
* as a percentage of the total fee payable to Experts. This fee
* is deducted from the amount paid by Callers to Experts.
* @param basisPoints The fee percentage expressed as basis points
*/
function setWinNetworkFee
(
uint256 basisPoints
)
external
requireIsOperational
requireContractOwner
{
require(basisPoints >= 0);
winNetworkFeeBasisPoints = basisPoints;
}
/**
* @dev Sets signup tokens allocated for each user (based on availability)
*
* @param tokens The number of tokens each user gets
*/
function setUserSignupTokens
(
uint256 tokens
)
external
requireIsOperational
requireContractOwner
{
require(tokens <= 10000);
userSignupJiffys = jiffysMultiplier.mul(tokens);
}
/**
* @dev Sets signup tokens allocated for each user (based on availability)
*
* @param tokens The number of tokens each referrer and referree get
*/
function setReferralSignupTokens
(
uint256 tokens
)
external
requireIsOperational
requireContractOwner
{
require(tokens <= 10000);
referralSignupJiffys = jiffysMultiplier.mul(tokens);
}
/**
* @dev Sets wallet to which ICO ETH funds are sent
*
* @param account The address to which ETH funds are sent
*/
function setIcoWallet
(
address account
)
external
requireIsOperational
requireContractOwner
{
require(account != address(0));
icoWallet = account;
}
/**
* @dev Authorizes a smart contract to call this contract
*
* @param account Address of the calling smart contract
*/
function authorizeContract
(
address account
)
public
requireIsOperational
requireContractOwner
{
require(account != address(0));
authorizedContracts[account] = 1;
}
/**
* @dev Deauthorizes a previously authorized smart contract from calling this contract
*
* @param account Address of the calling smart contract
*/
function deauthorizeContract
(
address account
)
external
requireIsOperational
requireContractOwner
{
require(account != address(0));
delete authorizedContracts[account];
}
/**
* @dev Checks if a contract is authorized to call this contract
*
* @param account Address of the calling smart contract
*/
function isContractAuthorized
(
address account
)
public
view
returns(bool)
{
return authorizedContracts[account] == 1;
}
/**
* @dev Sets the Wei to WHEN exchange rate
*
* @param rate Number of Wei for one WHEN token
*/
function setWeiExchangeRate
(
uint256 rate
)
external
requireIsOperational
requireContractOwner
{
require(rate >= 0); // Cannot set to less than 0.0001 ETH/₩
weiExchangeRate = rate;
}
/**
* @dev Sets the U.S. cents to WHEN exchange rate
*
* @param rate Number of cents for one WHEN token
*/
function setCentsExchangeRate
(
uint256 rate
)
external
requireIsOperational
requireContractOwner
{
require(rate >= 1);
centsExchangeRate = rate;
}
/**
* @dev Sets the account that will be used for Platform Manager functions
*
* @param account Account to replace existing Platform Manager
*/
function setPlatformManager
(
address account
)
external
requireIsOperational
requireContractOwner
{
require(account != address(0));
require(account != platformManager);
balances[account] = balances[account].add(balances[platformManager]);
balances[platformManager] = 0;
if (!users[account].isRegistered) {
users[account] = User(true, 0, 0, address(0));
registeredUserLookup.push(account);
}
platformManager = account;
}
/**
* @dev Checks if an account is the PlatformManager
*
* @param account Account to check
*/
function isPlatformManager
(
address account
)
public
view
returns(bool)
{
return account == platformManager;
}
/**
* @dev Checks if an account is the PlatformManager or SupportManager
*
* @param account Account to check
*/
function isPlatformOrSupportManager
(
address account
)
public
view
returns(bool)
{
return (account == platformManager) || (account == supportManager);
}
/**
* @dev Gets address of SupportManager
*
*/
function getSupportManager()
public
view
returns(address)
{
return supportManager;
}
/**
* @dev Checks if referral tokens are available
*
* referralSignupTokens is doubled because both referrer
* and recipient get referral tokens
*
* @return A bool indicating if referral tokens are available
*/
function isReferralSupported()
public
view
returns(bool)
{
uint256 requiredJiffys = referralSignupJiffys.mul(2);
return (referralJiffysBalance >= requiredJiffys) && (balances[platformManager] >= requiredJiffys);
}
/**
* @dev Checks if user is a registered user
*
* @param account The address which owns the funds.
* @return A bool indicating if user is a registered user.
*/
function isUserRegistered
(
address account
)
public
view
returns(bool)
{
return (account != address(0)) && users[account].isRegistered;
}
/**
* @dev Checks pre-reqs and handles user registration
*
* @param account The address which is to be registered
* @param creditAccount The address which contains token credits from CC purchase
* @param referrer The address referred the account
*/
function processRegisterUser
(
address account,
address creditAccount,
address referrer
)
private
{
require(account != address(0)); // No invalid account
require(!users[account].isRegistered); // No double registration
require(referrer == address(0) ? true : users[referrer].isRegistered); // Referrer, if present, must be a registered user
require(referrer != account); // User can't refer her/himself
// Initialize user with restricted jiffys
users[account] = User(true, 0, 0, referrer);
registeredUserLookup.push(account);
if (purchaseCredits[creditAccount].jiffys > 0) {
processPurchase(creditAccount, account, purchaseCredits[creditAccount].jiffys, purchaseCredits[creditAccount].purchaseTimestamp);
purchaseCredits[creditAccount].jiffys = 0;
delete purchaseCredits[creditAccount];
}
}
/**
* @dev Registers a user wallet with a referrer and deposits any applicable signup tokens
*
* @param account The wallet address
* @param creditAccount The address containing any tokens purchased with USD
* @param referrer The referring user address
* @return A uint256 with the user's token balance
*/
function registerUser
(
address account,
address creditAccount,
address referrer
)
public
requireIsOperational
requirePlatformManager
returns(uint256)
{
processRegisterUser(account, creditAccount, referrer);
UserRegister(account, balanceOf(account), 0); // Fire event
return balanceOf(account);
}
/**
* @dev Registers a user wallet with a referrer and deposits any applicable bonus tokens
*
* @param account The wallet address
* @param creditAccount The address containing any tokens purchased with USD
* @param referrer The referring user address
* @return A uint256 with the user's token balance
*/
function registerUserBonus
(
address account,
address creditAccount,
address referrer
)
external
requireIsOperational
requirePlatformManager
returns(uint256)
{
processRegisterUser(account, creditAccount, referrer);
// Allocate if there are any remaining signup tokens
uint256 jiffys = 0;
if ((incentiveJiffysBalance >= userSignupJiffys) && (balances[platformManager] >= userSignupJiffys)) {
incentiveJiffysBalance = incentiveJiffysBalance.sub(userSignupJiffys);
users[account].seedJiffys = users[account].seedJiffys.add(userSignupJiffys);
transfer(account, userSignupJiffys);
jiffys = userSignupJiffys;
}
UserRegister(account, balanceOf(account), jiffys); // Fire event
// Allocate referral tokens for both user and referrer if available
if ((referrer != address(0)) && isReferralSupported()) {
referralJiffysBalance = referralJiffysBalance.sub(referralSignupJiffys.mul(2));
// Referal tokens are restricted so it is necessary to update user's account
transfer(referrer, referralSignupJiffys);
users[referrer].seedJiffys = users[referrer].seedJiffys.add(referralSignupJiffys);
transfer(account, referralSignupJiffys);
users[account].seedJiffys = users[account].seedJiffys.add(referralSignupJiffys);
UserRefer(account, referrer, referralSignupJiffys); // Fire event
}
return balanceOf(account);
}
/**
* @dev Adds Jiffys to escrow for a user
*
* Escrows track the number of Jiffys that the user may owe another user.
* This function is called by the InterfaceData contract when a caller
* subscribes to a call.
*
* @param account The wallet address
* @param jiffys The number of Jiffys to put into escrow
*/
function depositEscrow
(
address account,
uint256 jiffys
)
external
requireIsOperational
{
if (jiffys > 0) {
require(isContractAuthorized(msg.sender) || isPlatformManager(msg.sender));
require(isUserRegistered(account));
require(spendableBalanceOf(account) >= jiffys);
users[account].interfaceEscrowJiffys = users[account].interfaceEscrowJiffys.add(jiffys);
}
}
/**
* @dev Refunds Jiffys from escrow for a user
*
* This function is called by the InterfaceData contract when a caller
* unsubscribes from a call.
*
* @param account The wallet address
* @param jiffys The number of Jiffys to remove from escrow
*/
function refundEscrow
(
address account,
uint256 jiffys
)
external
requireIsOperational
{
if (jiffys > 0) {
require(isContractAuthorized(msg.sender) || isPlatformManager(msg.sender));
require(isUserRegistered(account));
require(users[account].interfaceEscrowJiffys >= jiffys);
users[account].interfaceEscrowJiffys = users[account].interfaceEscrowJiffys.sub(jiffys);
}
}
/**
* @dev Handles payment for an Interface transaction
*
* This function is called by the InterfaceData contract when the front-end
* application makes a settle() call indicating that the transaction is
* complete and it's time to pay the Expert. To prevent unauthorized use
* the function is only callable by a previously authorized contract and
* is limited to paying out funds previously escrowed.
*
* @param payer The account paying (i.e. a caller)
* @param payee The account being paid (i.e. the Expert)
* @param referrer The account that referred payer to payee
* @param referralFeeBasisPoints The referral fee payable to referrer
* @param billableJiffys The number of Jiffys for payment
* @param escrowJiffys The number of Jiffys held in escrow for Interface being paid
*/
function pay
(
address payer,
address payee,
address referrer,
uint256 referralFeeBasisPoints,
uint256 billableJiffys,
uint256 escrowJiffys
)
external
requireIsOperational
returns(uint256, uint256)
{
require(isContractAuthorized(msg.sender));
require(billableJiffys >= 0);
require(users[payer].interfaceEscrowJiffys >= billableJiffys); // Only payment of Interface escrowed funds is allowed
require(users[payee].isRegistered);
// This function may be called if the Expert's surety is
// being forfeited. In that case, the payment is made to the
// Support and then funds will be distributed as appropriate
// to parties following a grievance process. Since the rules
// for forfeiture can get very complex, they are best handled
// off-contract. payee == supportManager indicates a forfeiture.
// First, release Payer escrow
users[payer].interfaceEscrowJiffys = users[payer].interfaceEscrowJiffys.sub(escrowJiffys);
uint256 referralFeeJiffys = 0;
uint256 winNetworkFeeJiffys = 0;
if (billableJiffys > 0) {
// Second, pay the payee
processPayment(payer, payee, billableJiffys);
// Payee is SupportManager if Expert surety is being forfeited, so skip referral and network fees
if (payee != supportManager) {
// Third, Payee pays Referrer and referral fees due
if ((referralFeeBasisPoints > 0) && (referrer != address(0)) && (users[referrer].isRegistered)) {
referralFeeJiffys = billableJiffys.mul(referralFeeBasisPoints).div(BASIS_POINTS_TO_PERCENTAGE); // Basis points to percentage conversion
processPayment(payee, referrer, referralFeeJiffys);
}
// Finally, Payee pays contract owner WIN network fee
if (winNetworkFeeBasisPoints > 0) {
winNetworkFeeJiffys = billableJiffys.mul(winNetworkFeeBasisPoints).div(BASIS_POINTS_TO_PERCENTAGE); // Basis points to percentage conversion
processPayment(payee, contractOwner, winNetworkFeeJiffys);
}
}
}
return(referralFeeJiffys, winNetworkFeeJiffys);
}
/**
* @dev Handles actual token transfer for payment
*
* @param payer The account paying
* @param payee The account being paid
* @param jiffys The number of Jiffys for payment
*/
function processPayment
(
address payer,
address payee,
uint256 jiffys
)
private
{
require(isUserRegistered(payer));
require(isUserRegistered(payee));
require(spendableBalanceOf(payer) >= jiffys);
balances[payer] = balances[payer].sub(jiffys);
balances[payee] = balances[payee].add(jiffys);
Transfer(payer, payee, jiffys);
// In the event the payer had received any signup tokens, their value
// would be stored in the seedJiffys property. When any contract payment
// is made, we reduce the seedJiffys number. seedJiffys tracks how many
// tokens are not allowed to be transferred out of an account. As a user
// makes payments to other users, those tokens have served their purpose
// of encouraging use of the network and are no longer are restricted.
if (users[payer].seedJiffys >= jiffys) {
users[payer].seedJiffys = users[payer].seedJiffys.sub(jiffys);
} else {
users[payer].seedJiffys = 0;
}
}
/**
* @dev Handles transfer of tokens for vesting grants
*
* This function is called by the TokenVesting contract. To prevent unauthorized
* use the function is only callable by a previously authorized contract.
*
* @param issuer The account granting tokens
* @param beneficiary The account being granted tokens
* @param vestedJiffys The number of vested Jiffys for immediate payment
* @param unvestedJiffys The number of unvested Jiffys to be placed in escrow
*/
function vestingGrant
(
address issuer,
address beneficiary,
uint256 vestedJiffys,
uint256 unvestedJiffys
)
external
requireIsOperational
{
require(isContractAuthorized(msg.sender));
require(spendableBalanceOf(issuer) >= unvestedJiffys.add(vestedJiffys));
// Any vestedJiffys are transferred immediately to the beneficiary
if (vestedJiffys > 0) {
balances[issuer] = balances[issuer].sub(vestedJiffys);
balances[beneficiary] = balances[beneficiary].add(vestedJiffys);
Transfer(issuer, beneficiary, vestedJiffys);
}
// Any unvestedJiffys are removed from the granting account balance
// A corresponding number of Jiffys is added to the granting account's
// vesting escrow balance.
balances[issuer] = balances[issuer].sub(unvestedJiffys);
vestingEscrows[issuer] = vestingEscrows[issuer].add(unvestedJiffys);
}
/**
* @dev Handles transfer of tokens for vesting revokes and releases
*
* This function is called by the TokenVesting contract. To prevent unauthorized
* use the function is only callable by a previously authorized contract.
*
* @param issuer The account granting tokens
* @param beneficiary The account being granted tokens
* @param jiffys The number of Jiffys for release or revoke
*/
function vestingTransfer
(
address issuer,
address beneficiary,
uint256 jiffys
)
external
requireIsOperational
{
require(isContractAuthorized(msg.sender));
require(vestingEscrows[issuer] >= jiffys);
vestingEscrows[issuer] = vestingEscrows[issuer].sub(jiffys);
balances[beneficiary] = balances[beneficiary].add(jiffys);
Transfer(issuer, beneficiary, jiffys);
}
/**
* @dev Gets an array of addresses registered with contract
*
* This can be used by API to enumerate all users
*/
function getRegisteredUsers()
external
view
requirePlatformManager
returns(address[])
{
return registeredUserLookup;
}
/**
* @dev Gets an array of addresses registered with contract
*
* This can be used by API to enumerate all users
*/
function getRegisteredUser
(
address account
)
external
view
requirePlatformManager
returns(uint256, uint256, uint256, address)
{
require(users[account].isRegistered);
return (balances[account], users[account].seedJiffys, users[account].interfaceEscrowJiffys, users[account].referrer);
}
/**
* @dev Returns ICO-related state information for use by API
*/
function getIcoInfo()
public
view
returns(bool, uint256, uint256, uint256, uint256, uint256)
{
return (
balances[icoOwner] > 0,
weiExchangeRate,
centsExchangeRate,
bonus20EndTimestamp,
bonus10EndTimestamp,
bonus5EndTimestamp
);
}
/********************************************************************************************/
/* TOKEN SALE */
/********************************************************************************************/
/**
* @dev Fallback function for buying ICO tokens. This is not expected to be called with
* default gas as it will most certainly fail.
*
*/
function()
external
payable
{
buy(msg.sender);
}
/**
* @dev Buy ICO tokens
*
* @param account Account that is buying tokens
*
*/
function buy
(
address account
)
public
payable
requireIsOperational
{
require(balances[icoOwner] > 0);
require(account != address(0));
require(msg.value >= weiExchangeRate); // Minimum 1 token
uint256 weiReceived = msg.value;
// Convert Wei to Jiffys based on the exchange rate
uint256 buyJiffys = weiReceived.mul(jiffysMultiplier).div(weiExchangeRate);
processPurchase(icoOwner, account, buyJiffys, now);
icoWallet.transfer(msg.value);
}
/**
* @dev Buy ICO tokens with USD
*
* @param account Account that is buying tokens
* @param cents Purchase amount in cents
*
*/
function buyUSD
(
address account,
uint256 cents
)
public
requireIsOperational
requirePlatformManager
{
require(balances[icoOwner] > 0);
require(account != address(0));
require(cents >= centsExchangeRate); // Minimum 1 token
// Convert Cents to Jiffys based on the exchange rate
uint256 buyJiffys = cents.mul(jiffysMultiplier).div(centsExchangeRate);
if (users[account].isRegistered) {
processPurchase(icoOwner, account, buyJiffys, now);
} else {
// Purchased credits will be transferred to account when user registers
// They are kept in a holding area until then. We deduct buy+bonus from
// icoOwner because that is the amount that will eventually be credited.
// However, we store the credit as buyJiffys so that the referral calculation
// will be against the buy amount and not the buy+bonus amount
uint256 totalJiffys = buyJiffys.add(calculatePurchaseBonus(buyJiffys, now));
balances[icoOwner] = balances[icoOwner].sub(totalJiffys);
balances[account] = balances[account].add(totalJiffys);
purchaseCredits[account] = PurchaseCredit(buyJiffys, now);
Transfer(icoOwner, account, buyJiffys);
}
}
/**
* @dev Process token purchase
*
* @param account Account that is buying tokens
* @param buyJiffys Number of Jiffys purchased
*
*/
function processPurchase
(
address source,
address account,
uint256 buyJiffys,
uint256 purchaseTimestamp
)
private
{
uint256 totalJiffys = buyJiffys.add(calculatePurchaseBonus(buyJiffys, purchaseTimestamp));
// Transfer purchased Jiffys to buyer
require(transferableBalanceOf(source) >= totalJiffys);
balances[source] = balances[source].sub(totalJiffys);
balances[account] = balances[account].add(totalJiffys);
Transfer(source, account, totalJiffys);
// If the buyer has a referrer attached to their profile, then
// transfer 3% of the purchased Jiffys to the referrer's account
if (users[account].isRegistered && (users[account].referrer != address(0))) {
address referrer = users[account].referrer;
uint256 referralJiffys = (buyJiffys.mul(BUYER_REFERRER_BOUNTY)).div(100);
if ((referralJiffys > 0) && (transferableBalanceOf(icoOwner) >= referralJiffys)) {
balances[icoOwner] = balances[icoOwner].sub(referralJiffys);
balances[referrer] = balances[referrer].add(referralJiffys);
Transfer(icoOwner, referrer, referralJiffys);
}
}
}
/**
* @dev Calculates ICO bonus tokens
*
* @param buyJiffys Number of Jiffys purchased
*
*/
function calculatePurchaseBonus
(
uint256 buyJiffys,
uint256 purchaseTimestamp
)
private
view
returns(uint256)
{
uint256 bonusPercentage = 0;
// Time-based bonus
if (purchaseTimestamp <= bonus5EndTimestamp) {
if (purchaseTimestamp <= bonus10EndTimestamp) {
if (purchaseTimestamp <= bonus20EndTimestamp) {
bonusPercentage = 20;
} else {
bonusPercentage = 10;
}
} else {
bonusPercentage = 5;
}
}
return (buyJiffys.mul(bonusPercentage)).div(100);
}
}
/*
LICENSE FOR SafeMath and TokenVesting
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
library SafeMath {
/* Copyright (c) 2016 Smart Contract Solutions, Inc. */
/* See License at end of file */
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
Checks if referral tokens are available referralSignupTokens is doubled because both referrer and recipient get referral tokens return A bool indicating if referral tokens are available/
|
function isReferralSupported()
public
view
returns(bool)
{
uint256 requiredJiffys = referralSignupJiffys.mul(2);
return (referralJiffysBalance >= requiredJiffys) && (balances[platformManager] >= requiredJiffys);
}
| 1,334,571
|
./full_match/5/0x17FB0da853309F723aba6d0c08E445a3384Ee7F7/sources/contracts/CrowdFunding.sol
|
_id is the id of campaign
|
function donateToCampaign(uint256 _id) public payable {
uint256 amount = msg.value;
Campaign storage campaign = campaigns[_id];
campaign.donators.push(msg.sender);
campaign.donations.push(amount);
if(sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
| 1,911,936
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "hardhat/console.sol";
import "./IContractRegistry.sol";
contract BatchCollection is ERC721, ERC721Enumerable, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
using Address for address;
event BatchMinted(address sender);
event BatchUpdated(address sender, string serialNumber, uint quantity);
event BatchRetirementConfirmed(uint256 tokenId);
address private _verifier;
/// @dev A mapping from batchs IDs to the address that owns them. All batches have
/// some valid owner address from the point of minting, then transfer
mapping (uint256 => address) public batchIndexToOwner;
address public contractRegistry;
Counters.Counter private _tokenIds;
// WIP: The fields and naming is subject to change
// required: projectIdentifier+vintage+serialNumber = unique
struct NFTData {
string projectIdentifier;
string vintage;
string serialNumber;
uint256 quantity;
bool confirmed;
}
mapping (uint256 => NFTData) public nftList;
constructor(address _contractRegistry) ERC721("ClaimCollection", "v0.1-Claim") {
contractRegistry = _contractRegistry;
}
// The verifier has the authority to confirm NFTs so ERC20's can be minted
modifier onlyVerifier() {
require(_verifier == _msgSender(), "BatchCollection: caller is not the owner");
_;
}
// Simple setter for verifier, there shall be multiple ones
function setVerifier (address verifier) public onlyOwner {
_verifier = verifier;
}
// Appointed verifier confirms that claim about retirement is valid
function confirmRetirement (uint256 tokenId) public onlyVerifier {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
nftList[tokenId].confirmed = true;
emit BatchRetirementConfirmed(tokenId);
}
function getProjectIdent(uint256 tokenId) public view returns (string memory) {
return nftList[tokenId].projectIdentifier;
}
function getQuantity(uint256 tokenId) public view returns (uint) {
return nftList[tokenId].quantity;
}
function getConfirmationStatus(uint256 tokenId) public view returns (bool) {
return nftList[tokenId].confirmed;
}
function getNftData(uint256 tokenId) public view returns (string memory, string memory, string memory, uint, bool) {
return (
nftList[tokenId].projectIdentifier,
nftList[tokenId].vintage,
nftList[tokenId].serialNumber,
nftList[tokenId].quantity,
nftList[tokenId].confirmed
);
}
// here for debugging/mock purposes. safeTransferFrom(...) is error prone with ethers.js
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
safeTransferFrom(from, to, tokenId, "");
}
function ownerBalanceOf(address owner) public view returns (uint256) {
uint256 balance = balanceOf(owner);
console.log("Owner balance is ", balance);
return (balance);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC721, ERC721Enumerable) {
if (to.isContract()) {
// Reverts if NFT is send a non official pERC20 contract
require(IContractRegistry(contractRegistry).checkERC20(to), "pERC20 contract is not official");
}
else {
super._beforeTokenTransfer(from, to, amount);
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
/// @notice Returns a list of all BatchIDs assigned to an address.
function tokensOfOwner(address _owner) external view returns(NFTData[] memory ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0)
{
// Return an empty array
return new NFTData[](0);
}
else
{
NFTData[] memory result = new NFTData[](tokenCount);
uint256 totalNfts = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all nfts have IDs starting at 1 and increasing
// sequentially up to the totalNfts count.
uint256 nftId;
for (nftId = 1; nftId <= totalNfts; nftId++) {
if (batchIndexToOwner[nftId] == _owner) {
result[resultIndex] = nftList[nftId];
resultIndex++;
}
}
return result;
}
}
/// @notice Returns a list of all BatchIDs assigned to an address.
function tokenIdsOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0)
{
// Return an empty array
return new uint256[](0);
}
else
{
uint256[] memory result = new uint256[](tokenCount);
uint256 totalNfts = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all nfts have IDs starting at 1 and increasing
// sequentially up to the totalNfts count.
uint256 nftId;
for (nftId = 1; nftId <= totalNfts; nftId++) {
if (batchIndexToOwner[nftId] == _owner) {
result[resultIndex] = nftId;
resultIndex++;
}
}
return result;
}
}
/// @notice Returns a list of all unconfirmed NFTs waiting for approval
function tokenizationRequests() external view returns(NFTData[] memory ownerTokens)
{
uint256 totalNfts = totalSupply();
uint256 resultIndex = 0;
NFTData[] memory result = new NFTData[](totalNfts);
// We count on the fact that all nfts have IDs starting at 1 and increasing
// sequentially up to the totalNfts count.
uint256 nftId;
for (nftId = 1; nftId <= totalNfts; nftId++)
{
if (nftList[nftId].confirmed == false)
{
result[resultIndex] = nftList[nftId];
resultIndex++;
}
}
return result;
}
// Entry function to bring offsets on-chain
// Mints an NFT claiming that 1 to n tons have been retired
function mintBatch (address to)
public
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
console.log("minting BRC to ", to);
console.log("newItemId is ", newItemId);
batchIndexToOwner[newItemId] = to;
_safeMint(to, newItemId);
nftList[newItemId].confirmed = false;
emit BatchMinted(to);
return newItemId;
}
// Updates NFT claiming that 1 to n tons have been retired
function updateBatchWithData(
address to,
uint256 tokenId,
string memory _projectIdentifier,
string memory _vintage,
string memory _serialNumber,
uint256 quantity)
public onlyVerifier
returns (uint256)
{
nftList[tokenId].projectIdentifier = _projectIdentifier;
nftList[tokenId].vintage = _vintage;
nftList[tokenId].serialNumber = _serialNumber;
nftList[tokenId].quantity = quantity;
emit BatchUpdated(to, _serialNumber, quantity);
return tokenId;
}
// LEGACY: Entry function to bring offsets on-chain
function mintBatchWithData(
address to,
string memory _projectIdentifier,
string memory _vintage,
string memory _serialNumber,
uint256 quantity)
public
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
console.log("minting to ", to);
console.log("newItemId is ", newItemId);
batchIndexToOwner[newItemId] = to;
_safeMint(to, newItemId);
nftList[newItemId].projectIdentifier = _projectIdentifier;
nftList[newItemId].vintage = _vintage;
nftList[newItemId].serialNumber = _serialNumber;
nftList[newItemId].quantity = quantity;
nftList[newItemId].confirmed = false;
return newItemId;
}
}
|
Updates NFT claiming that 1 to n tons have been retired
|
function updateBatchWithData(
address to,
uint256 tokenId,
string memory _projectIdentifier,
string memory _vintage,
string memory _serialNumber,
uint256 quantity)
public onlyVerifier
returns (uint256)
{
nftList[tokenId].projectIdentifier = _projectIdentifier;
nftList[tokenId].vintage = _vintage;
nftList[tokenId].serialNumber = _serialNumber;
nftList[tokenId].quantity = quantity;
emit BatchUpdated(to, _serialNumber, quantity);
return tokenId;
}
| 13,119,301
|
pragma solidity 0.4.19;
contract IConnections {
// Forward = the connection is from the Connection creator to the specified recipient
// Backwards = the connection is from the specified recipient to the Connection creator
enum Direction {NotApplicable, Forwards, Backwards, Invalid}
function createUser() external returns (address entityAddress);
function createUserAndConnection(address _connectionTo, bytes32 _connectionType, Direction _direction) external returns (address entityAddress);
function createVirtualEntity() external returns (address entityAddress);
function createVirtualEntityAndConnection(address _connectionTo, bytes32 _connectionType, Direction _direction) external returns (address entityAddress);
function editEntity(address _entity, bool _active, bytes32 _data) external;
function transferEntityOwnerPush(address _entity, address _newOwner) external;
function transferEntityOwnerPull(address _entity) external;
function addConnection(address _entity, address _connectionTo, bytes32 _connectionType, Direction _direction) public;
function editConnection(address _entity, address _connectionTo, bytes32 _connectionType, Direction _direction, bool _active, bytes32 _data, uint _expiration) external;
function removeConnection(address _entity, address _connectionTo, bytes32 _connectionType) external;
function isUser(address _entity) view public returns (bool isUserEntity);
function getEntity(address _entity) view external returns (bool active, address transferOwnerTo, bytes32 data, address owner);
function getConnection(address _entity, address _connectionTo, bytes32 _connectionType) view external returns (bool entityActive, bool connectionEntityActive, bool connectionActive, bytes32 data, Direction direction, uint expiration);
// ################## Events ################## //
event entityAdded(address indexed entity, address indexed owner);
event entityModified(address indexed entity, address indexed owner, bool indexed active, bytes32 data);
event entityOwnerChangeRequested(address indexed entity, address indexed oldOwner, address newOwner);
event entityOwnerChanged(address indexed entity, address indexed oldOwner, address newOwner);
event connectionAdded(address indexed entity, address indexed connectionTo, bytes32 connectionType, Direction direction);
event connectionModified(address indexed entity, address indexed connectionTo, bytes32 indexed connectionType, Direction direction, bool active, uint expiration);
event connectionRemoved(address indexed entity, address indexed connectionTo, bytes32 indexed connectionType);
event entityResolved(address indexed entityRequested, address indexed entityResolved);
}
/**
* @title Connections v0.2
* @dev The Connections contract records different connections between different types of entities.
*
* The contract has been designed for flexibility and scalability for use by anyone wishing to record different types of connections.
*
* Entities can be Users representing People, or Virtual Entities representing abstract types such as companies, objects, devices, robots etc...
* User entities are special: each Ethereum address that creates or controls a User entity can only ever create one User Entity.
* Each entity has an address to refer to it.
*
* Each entity has a number of connections to other entities, which are refered to using the entities address that the connection is to.
* Modifying or removing entities, or adding, modifying or removing connections can only be done by the entity owner.
*
* Each connection also has a type, a direction and an expiration. The use of these fields is up to the Dapp to define and interprete.
* Hashing a string of the connection name to create the connection type is suggested to obscure and diffuse types. Example bytes32 connection types:
* 0x30ed9383ab64b27cb4b70035e743294fe1a1c83eaf57eca05033b523d1fa4261 = keccak256("isAdvisorOf")
* 0xffe72ffb7d5cc4224f27ea8ad324f4b53b37835a76fc2b627b3d669180b75ecc = keccak256("isPartneredWith")
* 0xa64b51178a7ee9735fb96d8e7ffdebb455b02beb3b1e17a709b5c1beef797405 = keccak256("isEmployeeOf")
* 0x0079ca0c877589ba53b2e415a660827390d2c2a62123cef473009d003577b7f6 = keccak256("isColleagueOf")
*
*/
contract Connections is IConnections {
struct Entity {
bool active;
address transferOwnerTo;
address owner;
bytes32 data; // optional, this can link to IPFS or another off-chain storage location
mapping (address => mapping (bytes32 => Connection)) connections;
}
// Connection has a type and direction
struct Connection {
bool active;
bytes32 data; // optional, this can link to IPFS or another off-chain storage location
Direction direction;
uint expiration; // optional, unix timestamp or latest date to assume this connection is valid, 0 as no expiration
}
mapping (address => Entity) public entities;
mapping (address => address) public entityOfUser;
uint256 public virtualEntitiesCreated = 0;
// ################## Constructor and Fallback function ################## //
/**
* Constructor
*/
function Connections() public {}
/**
* Fallback function that cannot be called and will not accept Ether
* Note that Ether can still be forced to this contract with a contract suicide()
*/
function () external {
revert();
}
// ################## External function ################## //
/**
* Creates a new user entity with an address of the msg.sender
*/
function createUser() external returns (address entityAddress) {
entityAddress = msg.sender;
assert(entityOfUser[msg.sender] == address(0));
createEntity(entityAddress, msg.sender);
entityOfUser[msg.sender] = entityAddress;
}
/**
* Creates a new user entity and a connection in one transaction
* @param _connectionTo - the address of the entity to connect to
* @param _connectionType - hash of the connection type
* @param _direction - indicates the direction of the connection type
*/
function createUserAndConnection(
address _connectionTo,
bytes32 _connectionType,
Direction _direction
)
external returns (address entityAddress)
{
entityAddress = msg.sender;
assert(entityOfUser[msg.sender] == address(0));
createEntity(entityAddress, msg.sender);
entityOfUser[msg.sender] = entityAddress;
addConnection(entityAddress, _connectionTo, _connectionType, _direction);
}
/**
* Creates a new virtual entity that is assigned to a unique address
*/
function createVirtualEntity() external returns (address entityAddress) {
entityAddress = createVirtualAddress();
createEntity(entityAddress, msg.sender);
}
/**
* Creates a new virtual entity and a connection in one transaction
* @param _connectionTo - the address of the entity to connect to
* @param _connectionType - hash of the connection type
* @param _direction - indicates the direction of the connection type
*/
function createVirtualEntityAndConnection(
address _connectionTo,
bytes32 _connectionType,
Direction _direction
)
external returns (address entityAddress)
{
entityAddress = createVirtualAddress();
createEntity(entityAddress, msg.sender);
addConnection(entityAddress, _connectionTo, _connectionType, _direction);
}
/**
* Edits data or active boolean of an entity that the msg sender is an owner of
* This can be used to activate or deactivate an entity
* @param _entity - the address of the entity to edit
* @param _active - boolean to indicate if the entity is active or not
* @param _data - data to be used to locate off-chain information about the user
*/
function editEntity(address _entity, bool _active, bytes32 _data) external {
address resolvedEntity = resolveEntityAddressAndOwner(_entity);
Entity storage entity = entities[resolvedEntity];
entity.active = _active;
entity.data = _data;
entityModified(_entity, msg.sender, _active, _data);
}
/**
* Creates a request to transfer the ownership of an entity which must be accepted.
* To cancel a request execute this function with _newOwner = address(0)
* @param _entity - the address of the entity to transfer
* @param _newOwner - the address of the new owner that will then have the exclusive permissions to control the entity
*/
function transferEntityOwnerPush(address _entity, address _newOwner) external {
address resolvedEntity = resolveEntityAddressAndOwner(_entity);
entities[resolvedEntity].transferOwnerTo = _newOwner;
entityOwnerChangeRequested(_entity, msg.sender, _newOwner);
}
/**
* Accepts a request to transfer the ownership of an entity
* @param _entity - the address of the entity to get ownership of
*/
function transferEntityOwnerPull(address _entity) external {
address resolvedEntity = resolveEntityAddress(_entity);
emitEntityResolution(_entity, resolvedEntity);
Entity storage entity = entities[resolvedEntity];
require(entity.transferOwnerTo == msg.sender);
if (isUser(resolvedEntity)) { // This is a user entity
assert(entityOfUser[msg.sender] == address(0) ||
entityOfUser[msg.sender] == resolvedEntity);
entityOfUser[msg.sender] = resolvedEntity;
}
address oldOwner = entity.owner;
entity.owner = entity.transferOwnerTo;
entity.transferOwnerTo = address(0);
entityOwnerChanged(_entity, oldOwner, msg.sender);
}
/**
* Edits a connection to another entity
* @param _entity - the address of the entity to edit the connection of
* @param _connectionTo - the address of the entity to connect to
* @param _connectionType - hash of the connection type
* @param _active - boolean to indicate if the connection is active or not
* @param _direction - indicates the direction of the connection type
* @param _expiration - number to indicate the expiration of the connection
*/
function editConnection(
address _entity,
address _connectionTo,
bytes32 _connectionType,
Direction _direction,
bool _active,
bytes32 _data,
uint _expiration
)
external
{
address resolvedEntity = resolveEntityAddressAndOwner(_entity);
address resolvedConnectionEntity = resolveEntityAddress(_connectionTo);
emitEntityResolution(_connectionTo, resolvedConnectionEntity);
Entity storage entity = entities[resolvedEntity];
Connection storage connection = entity.connections[resolvedConnectionEntity][_connectionType];
connection.active = _active;
connection.direction = _direction;
connection.data = _data;
connection.expiration = _expiration;
connectionModified(_entity, _connectionTo, _connectionType, _direction, _active, _expiration);
}
/**
* Removes a connection from the entities connections mapping.
* If this is the last connection of any type to the _connectionTo address, then the removeConnection function should also be called to clean up the Entity
* @param _entity - the address of the entity to edit the connection of
* @param _connectionTo - the address of the entity to connect to
* @param _connectionType - hash of the connection type
*/
function removeConnection(address _entity, address _connectionTo, bytes32 _connectionType) external {
address resolvedEntity = resolveEntityAddressAndOwner(_entity);
address resolvedConnectionEntity = resolveEntityAddress(_connectionTo);
emitEntityResolution(_connectionTo,resolvedConnectionEntity);
Entity storage entity = entities[resolvedEntity];
delete entity.connections[resolvedConnectionEntity][_connectionType];
connectionRemoved(_entity, _connectionTo, _connectionType); // TBD: @haresh should we use resolvedEntity and resolvedConnectionEntity here?
}
/**
* Returns the sha256 hash of a string. Useful for looking up the bytes32 values are for connection types.
* Note this function is designed to be called off-chain for convenience, it is not used by any functions internally and does not change contract state
* @param _string - string to hash
* @return result - the hash of the string
*/
function sha256ofString(string _string) external pure returns (bytes32 result) {
result = keccak256(_string);
}
/**
* Returns all the fields of an entity
* @param _entity - the address of the entity to retrieve
* @return (active, transferOwnerTo, data, owner) - a tuple containing the active flag, transfer status, data field and owner of an entity
*/
function getEntity(address _entity) view external returns (bool active, address transferOwnerTo, bytes32 data, address owner) {
address resolvedEntity = resolveEntityAddress(_entity);
Entity storage entity = entities[resolvedEntity];
return (entity.active, entity.transferOwnerTo, entity.data, entity.owner);
}
/**
* Returns details of a connection
* @param _entity - the address of the entity which created the
* @return (entityActive, connectionEntityActive, connectionActive, data, direction, expiration)
* - tupple containing the entity active and the connection fields
*/
function getConnection(
address _entity,
address _connectionTo,
bytes32 _connectionType
)
view external returns (
bool entityActive,
bool connectionEntityActive,
bool connectionActive,
bytes32 data,
Direction direction,
uint expiration
){
address resolvedEntity = resolveEntityAddress(_entity);
address resolvedConnectionEntity = resolveEntityAddress(_connectionTo);
Entity storage entity = entities[resolvedEntity];
Connection storage connection = entity.connections[resolvedConnectionEntity][_connectionType];
return (entity.active, entities[resolvedConnectionEntity].active, connection.active, connection.data, connection.direction, connection.expiration);
}
// ################## Public function ################## //
/**
* Creates a new connection to another entity
* @param _entity - the address of the entity to add a connection to
* @param _connectionTo - the address of the entity to connect to
* @param _connectionType - hash of the connection type
* @param _direction - indicates the direction of the connection type
*/
function addConnection(
address _entity,
address _connectionTo,
bytes32 _connectionType,
Direction _direction
)
public
{
address resolvedEntity = resolveEntityAddressAndOwner(_entity);
address resolvedEntityConnection = resolveEntityAddress(_connectionTo);
emitEntityResolution(_connectionTo, resolvedEntityConnection);
Entity storage entity = entities[resolvedEntity];
assert(!entity.connections[resolvedEntityConnection][_connectionType].active);
Connection storage connection = entity.connections[resolvedEntityConnection][_connectionType];
connection.active = true;
connection.direction = _direction;
connectionAdded(_entity, _connectionTo, _connectionType, _direction);
}
/**
* Returns true if an entity is a user, false if a virtual entity or fails if is not an entity
* @param _entity - the address of the entity
* @return isUserEntity - true if the entity was created with createUser(), false if the entity is created using createVirtualEntity()
*/
function isUser(address _entity) view public returns (bool isUserEntity) {
address resolvedEntity = resolveEntityAddress(_entity);
assert(entities[resolvedEntity].active); // Make sure the user is active, otherwise this function call is invalid
address owner = entities[resolvedEntity].owner;
isUserEntity = (resolvedEntity == entityOfUser[owner]);
}
// ################## Internal functions ################## //
/**
* Creates a new entity at a specified address
*/
function createEntity(address _entityAddress, address _owner) internal {
require(!entities[_entityAddress].active); // Ensure the new entity address is not in use, prevents forceful takeover off addresses
Entity storage entity = entities[_entityAddress];
entity.active = true;
entity.owner = _owner;
entityAdded(_entityAddress, _owner);
}
/**
* Returns a new unique deterministic address that has not been used before
*/
function createVirtualAddress() internal returns (address virtualAddress) {
virtualAddress = address(keccak256(safeAdd(virtualEntitiesCreated,block.number)));
virtualEntitiesCreated = safeAdd(virtualEntitiesCreated,1);
}
/**
* Emits an event if an entity resolution took place. Separated out as it would impact
* view only functions which need entity resolution as well.
*/
function emitEntityResolution(address _entity, address _resolvedEntity) internal {
if (_entity != _resolvedEntity)
entityResolved(_entity,_resolvedEntity);
}
/**
* Returns the correct entity address resolved based on entityOfUser mapping
*/
function resolveEntityAddress(address _entityAddress) internal view returns (address resolvedAddress) {
if (entityOfUser[_entityAddress] != address(0) && entityOfUser[_entityAddress] != _entityAddress) {
resolvedAddress = entityOfUser[_entityAddress];
} else {
resolvedAddress = _entityAddress;
}
}
/**
* Returns the correct entity address resolved based on entityOfUser mapping and also reverts if the
* resolved if it is owned by the message sender
* sender.
*/
function resolveEntityAddressAndOwner(address _entityAddress) internal returns (address entityAddress) {
entityAddress = resolveEntityAddress(_entityAddress);
emitEntityResolution(_entityAddress, entityAddress);
require(entities[entityAddress].owner == msg.sender);
}
/**
* Adds two numbers and returns result throws in case an overflow occurs.
*/
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
assert(z >= x);
return z;
}
}
|
External function Creates a new user entity with an address of the msg.sender/
|
function createUser() external returns (address entityAddress) {
entityAddress = msg.sender;
assert(entityOfUser[msg.sender] == address(0));
createEntity(entityAddress, msg.sender);
entityOfUser[msg.sender] = entityAddress;
}
| 6,630,465
|
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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 is Initializable {
// 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-ethereum-package/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-ethereum-package/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-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.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 {ERC20Mintable}.
*
* 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 Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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 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 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 {
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);
}
/** @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 {
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);
}
/**
* @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 {
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);
}
/**
* @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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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-ethereum-package/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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-ethereum-package/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: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
// File: @aragon/court/contracts/lib/Checkpointing.sol
pragma solidity ^0.5.8;
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
// File: @aragon/court/contracts/lib/os/Uint256Helpers.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: contracts/InitializableV2.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* Wrapper around OpenZeppelin's Initializable contract.
* Exposes initialized state management to ensure logic contract functions cannot be called before initialization.
* This is needed because OZ's Initializable contract no longer exposes initialized state variable.
* https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol
*/
contract InitializableV2 is Initializable {
bool private isInitialized;
string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized";
/**
* @notice wrapper function around parent contract Initializable's `initializable` modifier
* initializable modifier ensures this function can only be called once by each deployed child contract
* sets isInitialized flag to true to which is used by _requireIsInitialized()
*/
function initialize() public initializer {
isInitialized = true;
}
/**
* @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure
* contract is initialized before functions can be called.
*/
function _requireIsInitialized() internal view {
require(isInitialized == true, ERROR_NOT_INITIALIZED);
}
/**
* @notice Exposes isInitialized bool var to child contracts with read-only access
*/
function _isInitialized() internal view returns (bool) {
return isInitialized;
}
}
// File: @openzeppelin/contracts-ethereum-package/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 aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = 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 _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;
}
uint256[50] private ______gap;
}
// File: contracts/registry/Registry.sol
pragma solidity ^0.5.0;
/**
* @title Central hub for Audius protocol. It stores all contract addresses to facilitate
* external access and enable version management.
*/
contract Registry is InitializableV2, Ownable {
using SafeMath for uint256;
/**
* @dev addressStorage mapping allows efficient lookup of current contract version
* addressStorageHistory maintains record of all contract versions
*/
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => address[]) private addressStorageHistory;
event ContractAdded(
bytes32 indexed _name,
address indexed _address
);
event ContractRemoved(
bytes32 indexed _name,
address indexed _address
);
event ContractUpgraded(
bytes32 indexed _name,
address indexed _oldAddress,
address indexed _newAddress
);
function initialize() public initializer {
/// @notice Ownable.initialize(address _sender) sets contract owner to _sender.
Ownable.initialize(msg.sender);
InitializableV2.initialize();
}
// ========================================= Setters =========================================
/**
* @notice addContract registers contract name to address mapping under given registry key
* @param _name - registry key that will be used for lookups
* @param _address - address of contract
*/
function addContract(bytes32 _name, address _address) external onlyOwner {
_requireIsInitialized();
require(
addressStorage[_name] == address(0x00),
"Registry: Contract already registered with given name."
);
require(
_address != address(0x00),
"Registry: Cannot register zero address."
);
setAddress(_name, _address);
emit ContractAdded(_name, _address);
}
/**
* @notice removes contract address registered under given registry key
* @param _name - registry key for lookup
*/
function removeContract(bytes32 _name) external onlyOwner {
_requireIsInitialized();
address contractAddress = addressStorage[_name];
require(
contractAddress != address(0x00),
"Registry: Cannot remove - no contract registered with given _name."
);
setAddress(_name, address(0x00));
emit ContractRemoved(_name, contractAddress);
}
/**
* @notice replaces contract address registered under given key with provided address
* @param _name - registry key for lookup
* @param _newAddress - new contract address to register under given key
*/
function upgradeContract(bytes32 _name, address _newAddress) external onlyOwner {
_requireIsInitialized();
address oldAddress = addressStorage[_name];
require(
oldAddress != address(0x00),
"Registry: Cannot upgrade - no contract registered with given _name."
);
require(
_newAddress != address(0x00),
"Registry: Cannot upgrade - cannot register zero address."
);
setAddress(_name, _newAddress);
emit ContractUpgraded(_name, oldAddress, _newAddress);
}
// ========================================= Getters =========================================
/**
* @notice returns contract address registered under given registry key
* @param _name - registry key for lookup
* @return contractAddr - address of contract registered under given registry key
*/
function getContract(bytes32 _name) external view returns (address contractAddr) {
_requireIsInitialized();
return addressStorage[_name];
}
/// @notice overloaded getContract to return explicit version of contract
function getContract(bytes32 _name, uint256 _version) external view
returns (address contractAddr)
{
_requireIsInitialized();
// array length for key implies version number
require(
_version <= addressStorageHistory[_name].length,
"Registry: Index out of range _version."
);
return addressStorageHistory[_name][_version.sub(1)];
}
/**
* @notice Returns the number of versions for a contract key
* @param _name - registry key for lookup
* @return number of contract versions
*/
function getContractVersionCount(bytes32 _name) external view returns (uint256) {
_requireIsInitialized();
return addressStorageHistory[_name].length;
}
// ========================================= Private functions =========================================
/**
* @param _key the key for the contract address
* @param _value the contract address
*/
function setAddress(bytes32 _key, address _value) private {
// main map for cheap lookup
addressStorage[_key] = _value;
// keep track of contract address history
addressStorageHistory[_key].push(_value);
}
}
// File: contracts/Governance.sol
pragma solidity ^0.5.0;
contract Governance is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"Governance: Only callable by self"
);
string private constant ERROR_INVALID_VOTING_PERIOD = (
"Governance: Requires non-zero _votingPeriod"
);
string private constant ERROR_INVALID_REGISTRY = (
"Governance: Requires non-zero _registryAddress"
);
string private constant ERROR_INVALID_VOTING_QUORUM = (
"Governance: Requires _votingQuorumPercent between 1 & 100"
);
/**
* @notice Address and contract instance of Audius Registry. Used to ensure this contract
* can only govern contracts that are registered in the Audius Registry.
*/
Registry private registry;
/// @notice Address of Audius staking contract, used to permission Governance method calls
address private stakingAddress;
/// @notice Address of Audius ServiceProvider contract, used to permission Governance method calls
address private serviceProviderFactoryAddress;
/// @notice Address of Audius DelegateManager contract, used to permission Governance method calls
address private delegateManagerAddress;
/// @notice Period in blocks for which a governance proposal is open for voting
uint256 private votingPeriod;
/// @notice Number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
uint256 private executionDelay;
/// @notice Required minimum percentage of total stake to have voted to consider a proposal valid
/// Percentaged stored as a uint256 between 0 & 100
/// Calculated as: 100 * sum of voter stakes / total staked in Staking (at proposal submission block)
uint256 private votingQuorumPercent;
/// @notice Max number of InProgress proposals possible at once
/// @dev uint16 gives max possible value of 65,535
uint16 private maxInProgressProposals;
/**
* @notice Address of account that has special Governance permissions. Can veto proposals
* and execute transactions directly on contracts.
*/
address private guardianAddress;
/***** Enums *****/
/**
* @notice All Proposal Outcome states.
* InProgress - Proposal is active and can be voted on.
* Rejected - Proposal votingPeriod has closed and vote failed to pass. Proposal will not be executed.
* ApprovedExecuted - Proposal votingPeriod has closed and vote passed. Proposal was successfully executed.
* QuorumNotMet - Proposal votingPeriod has closed and votingQuorumPercent was not met. Proposal will not be executed.
* ApprovedExecutionFailed - Proposal vote passed, but transaction execution failed.
* Evaluating - Proposal vote passed, and evaluateProposalOutcome function is currently running.
* This status is transiently used inside that function to prevent re-entrancy.
* Vetoed - Proposal was vetoed by Guardian.
* TargetContractAddressChanged - Proposal considered invalid since target contract address changed
* TargetContractCodeHashChanged - Proposal considered invalid since code has at target contract address has changed
*/
enum Outcome {
InProgress,
Rejected,
ApprovedExecuted,
QuorumNotMet,
ApprovedExecutionFailed,
Evaluating,
Vetoed,
TargetContractAddressChanged,
TargetContractCodeHashChanged
}
/**
* @notice All Proposal Vote states for a voter.
* None - The default state, for any account that has not previously voted on this Proposal.
* No - The account voted No on this Proposal.
* Yes - The account voted Yes on this Proposal.
* @dev Enum values map to uints, so first value in Enum always is 0.
*/
enum Vote {None, No, Yes}
struct Proposal {
uint256 proposalId;
address proposer;
uint256 submissionBlockNumber;
bytes32 targetContractRegistryKey;
address targetContractAddress;
uint256 callValue;
string functionSignature;
bytes callData;
Outcome outcome;
uint256 voteMagnitudeYes;
uint256 voteMagnitudeNo;
uint256 numVotes;
mapping(address => Vote) votes;
mapping(address => uint256) voteMagnitudes;
bytes32 contractHash;
}
/***** Proposal storage *****/
/// @notice ID of most recently created proposal. Ids are monotonically increasing and 1-indexed.
uint256 lastProposalId = 0;
/// @notice mapping of proposalId to Proposal struct with all proposal state
mapping(uint256 => Proposal) proposals;
/// @notice array of proposals with InProgress state
uint256[] inProgressProposals;
/***** Events *****/
event ProposalSubmitted(
uint256 indexed _proposalId,
address indexed _proposer,
string _name,
string _description
);
event ProposalVoteSubmitted(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake
);
event ProposalVoteUpdated(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake,
Vote _previousVote
);
event ProposalOutcomeEvaluated(
uint256 indexed _proposalId,
Outcome indexed _outcome,
uint256 _voteMagnitudeYes,
uint256 _voteMagnitudeNo,
uint256 _numVotes
);
event ProposalTransactionExecuted(
uint256 indexed _proposalId,
bool indexed _success,
bytes _returnData
);
event GuardianTransactionExecuted(
address indexed _targetContractAddress,
uint256 _callValue,
string indexed _functionSignature,
bytes indexed _callData,
bytes _returnData
);
event ProposalVetoed(uint256 indexed _proposalId);
event RegistryAddressUpdated(address indexed _newRegistryAddress);
event GuardianshipTransferred(address indexed _newGuardianAddress);
event VotingPeriodUpdated(uint256 indexed _newVotingPeriod);
event ExecutionDelayUpdated(uint256 indexed _newExecutionDelay);
event VotingQuorumPercentUpdated(uint256 indexed _newVotingQuorumPercent);
event MaxInProgressProposalsUpdated(uint256 indexed _newMaxInProgressProposals);
/**
* @notice Initialize the Governance contract
* @dev _votingPeriod <= DelegateManager.undelegateLockupDuration
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @param _registryAddress - address of the registry proxy contract
* @param _votingPeriod - period in blocks for which a governance proposal is open for voting
* @param _executionDelay - number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
* @param _votingQuorumPercent - required minimum percentage of total stake to have voted to consider a proposal valid
* @param _maxInProgressProposals - max number of InProgress proposals possible at once
* @param _guardianAddress - address of account that has special Governance permissions
*/
function initialize(
address _registryAddress,
uint256 _votingPeriod,
uint256 _executionDelay,
uint256 _votingQuorumPercent,
uint16 _maxInProgressProposals,
address _guardianAddress
) public initializer {
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
// executionDelay does not have to be non-zero
executionDelay = _executionDelay;
require(
_maxInProgressProposals > 0,
"Governance: Requires non-zero _maxInProgressProposals"
);
maxInProgressProposals = _maxInProgressProposals;
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
require(
_guardianAddress != address(0x00),
"Governance: Requires non-zero _guardianAddress"
);
guardianAddress = _guardianAddress; //Guardian address becomes the only party
InitializableV2.initialize();
}
// ========================================= Governance Actions =========================================
/**
* @notice Submit a proposal for vote. Only callable by addresses with non-zero total active stake.
* total active stake = total active deployer stake + total active delegator stake
*
* @dev _name and _description length is not enforced since they aren't stored on-chain and only event emitted
*
* @param _targetContractRegistryKey - Registry key for the contract concerning this proposal
* @param _callValue - amount of wei to pass with function call if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
* @param _name - Text name of proposal to be emitted in event
* @param _description - Text description of proposal to be emitted in event
*
* @return - ID of new proposal
*/
function submitProposal(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData,
string calldata _name,
string calldata _description
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
address proposer = msg.sender;
// Require all InProgress proposals that can be evaluated have been evaluated before new proposal submission
require(
this.inProgressProposalsAreUpToDate(),
"Governance: Cannot submit new proposal until all evaluatable InProgress proposals are evaluated."
);
// Require new proposal submission would not push number of InProgress proposals over max number
require(
inProgressProposals.length < maxInProgressProposals,
"Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire."
);
// Require proposer has non-zero total active stake or is guardian address
require(
_calculateAddressActiveStake(proposer) > 0 || proposer == guardianAddress,
"Governance: Proposer must be address with non-zero total active stake or be guardianAddress."
);
// Require _targetContractRegistryKey points to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
// Require non-zero description length
require(bytes(_description).length > 0, "Governance: _description length must be > 0");
// Require non-zero name length
require(bytes(_name).length > 0, "Governance: _name length must be > 0");
// set proposalId
uint256 newProposalId = lastProposalId.add(1);
// Store new Proposal obj in proposals mapping
proposals[newProposalId] = Proposal({
proposalId: newProposalId,
proposer: proposer,
submissionBlockNumber: block.number,
targetContractRegistryKey: _targetContractRegistryKey,
targetContractAddress: targetContractAddress,
callValue: _callValue,
functionSignature: _functionSignature,
callData: _callData,
outcome: Outcome.InProgress,
voteMagnitudeYes: 0,
voteMagnitudeNo: 0,
numVotes: 0,
contractHash: _getCodeHash(targetContractAddress)
/* votes: mappings are auto-initialized to default state */
/* voteMagnitudes: mappings are auto-initialized to default state */
});
// Append new proposalId to inProgressProposals array
inProgressProposals.push(newProposalId);
emit ProposalSubmitted(
newProposalId,
proposer,
_name,
_description
);
lastProposalId = newProposalId;
return newProposalId;
}
/**
* @notice Vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function submitVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Require voter has non-zero total active stake
uint256 voterActiveStake = _calculateAddressActiveStake(voter);
require(
voterActiveStake > 0,
"Governance: Voter must be address with non-zero total active stake."
);
// Require previous vote is None
require(
proposals[_proposalId].votes[voter] == Vote.None,
"Governance: To update previous vote, call updateVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record vote
proposals[_proposalId].votes[voter] = _vote;
// Record voteMagnitude for voter
proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake;
// Update proposal cumulative vote magnitudes
if (_vote == Vote.Yes) {
_increaseVoteMagnitudeYes(_proposalId, voterActiveStake);
} else {
_increaseVoteMagnitudeNo(_proposalId, voterActiveStake);
}
// Increment proposal numVotes
proposals[_proposalId].numVotes = proposals[_proposalId].numVotes.add(1);
emit ProposalVoteSubmitted(
_proposalId,
voter,
_vote,
voterActiveStake
);
}
/**
* @notice Update previous vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function updateVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Retrieve previous vote
Vote previousVote = proposals[_proposalId].votes[voter];
// Require previous vote is not None
require(
previousVote != Vote.None,
"Governance: To submit new vote, call submitVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record updated vote
proposals[_proposalId].votes[voter] = _vote;
// Update vote magnitudes, using vote magnitude from when previous vote was submitted
uint256 voteMagnitude = proposals[_proposalId].voteMagnitudes[voter];
if (previousVote == Vote.Yes && _vote == Vote.No) {
_decreaseVoteMagnitudeYes(_proposalId, voteMagnitude);
_increaseVoteMagnitudeNo(_proposalId, voteMagnitude);
} else if (previousVote == Vote.No && _vote == Vote.Yes) {
_decreaseVoteMagnitudeNo(_proposalId, voteMagnitude);
_increaseVoteMagnitudeYes(_proposalId, voteMagnitude);
}
// If _vote == previousVote, no changes needed to vote magnitudes.
// Do not update numVotes
emit ProposalVoteUpdated(
_proposalId,
voter,
_vote,
voteMagnitude,
previousVote
);
}
/**
* @notice Once the voting period + executionDelay for a proposal has ended, evaluate the outcome and
* execute the proposal if voting quorum met & vote passes.
* To pass, stake-weighted vote must be > 50% Yes.
* @dev Requires that caller is an active staker at the time the proposal is created
* @param _proposalId - id of the proposal
* @return Outcome of proposal evaluation
*/
function evaluateProposalOutcome(uint256 _proposalId)
external returns (Outcome)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
// Require proposal has not already been evaluated.
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Can only evaluate InProgress proposal."
);
// Re-entrancy should not be possible here since this switches the status of the
// proposal to 'Evaluating' so it should fail the status is 'InProgress' check
proposals[_proposalId].outcome = Outcome.Evaluating;
// Require proposal votingPeriod + executionDelay have ended.
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod).add(executionDelay);
require(
block.number > endBlockNumber,
"Governance: Proposal votingPeriod & executionDelay must end before evaluation."
);
address targetContractAddress = registry.getContract(
proposals[_proposalId].targetContractRegistryKey
);
Outcome outcome;
// target contract address changed -> close proposal without execution.
if (targetContractAddress != proposals[_proposalId].targetContractAddress) {
outcome = Outcome.TargetContractAddressChanged;
}
// target contract code hash changed -> close proposal without execution.
else if (_getCodeHash(targetContractAddress) != proposals[_proposalId].contractHash) {
outcome = Outcome.TargetContractCodeHashChanged;
}
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) {
outcome = Outcome.QuorumNotMet;
}
// votingQuorumPercent met & vote passed -> execute proposed transaction & close proposal.
else if (
proposals[_proposalId].voteMagnitudeYes > proposals[_proposalId].voteMagnitudeNo
) {
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
proposals[_proposalId].callValue,
proposals[_proposalId].functionSignature,
proposals[_proposalId].callData
);
emit ProposalTransactionExecuted(
_proposalId,
success,
returnData
);
// Proposal outcome depends on success of transaction execution.
if (success) {
outcome = Outcome.ApprovedExecuted;
} else {
outcome = Outcome.ApprovedExecutionFailed;
}
}
// votingQuorumPercent met & vote did not pass -> close proposal without transaction execution.
else {
outcome = Outcome.Rejected;
}
// This records the final outcome in the proposals mapping
proposals[_proposalId].outcome = outcome;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalOutcomeEvaluated(
_proposalId,
outcome,
proposals[_proposalId].voteMagnitudeYes,
proposals[_proposalId].voteMagnitudeNo,
proposals[_proposalId].numVotes
);
return outcome;
}
/**
* @notice Action limited to the guardian address that can veto a proposal
* @param _proposalId - id of the proposal
*/
function vetoProposal(uint256 _proposalId) external {
_requireIsInitialized();
_requireValidProposalId(_proposalId);
require(
msg.sender == guardianAddress,
"Governance: Only guardian can veto proposals."
);
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Cannot veto inactive proposal."
);
proposals[_proposalId].outcome = Outcome.Vetoed;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalVetoed(_proposalId);
}
// ========================================= Config Setters =========================================
/**
* @notice Set the Staking address
* @dev Only callable by self via _executeTransaction
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_stakingAddress != address(0x00), "Governance: Requires non-zero _stakingAddress");
stakingAddress = _stakingAddress;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by self via _executeTransaction
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_serviceProviderFactoryAddress != address(0x00),
"Governance: Requires non-zero _serviceProviderFactoryAddress"
);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by self via _executeTransaction
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_delegateManagerAddress != address(0x00),
"Governance: Requires non-zero _delegateManagerAddress"
);
delegateManagerAddress = _delegateManagerAddress;
}
/**
* @notice Set the voting period for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingPeriod - new voting period
*/
function setVotingPeriod(uint256 _votingPeriod) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
emit VotingPeriodUpdated(_votingPeriod);
}
/**
* @notice Set the voting quorum percentage for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingQuorumPercent - new voting period
*/
function setVotingQuorumPercent(uint256 _votingQuorumPercent) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
emit VotingQuorumPercentUpdated(_votingQuorumPercent);
}
/**
* @notice Set the Registry address
* @dev Only callable by self via _executeTransaction
* @param _registryAddress - address for new Registry contract
*/
function setRegistryAddress(address _registryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
emit RegistryAddressUpdated(_registryAddress);
}
/**
* @notice Set the max number of concurrent InProgress proposals
* @dev Only callable by self via _executeTransaction
* @param _newMaxInProgressProposals - new value for maxInProgressProposals
*/
function setMaxInProgressProposals(uint16 _newMaxInProgressProposals) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_newMaxInProgressProposals > 0,
"Governance: Requires non-zero _newMaxInProgressProposals"
);
maxInProgressProposals = _newMaxInProgressProposals;
emit MaxInProgressProposalsUpdated(_newMaxInProgressProposals);
}
/**
* @notice Set the execution delay for a proposal
* @dev Only callable by self via _executeTransaction
* @param _newExecutionDelay - new value for executionDelay
*/
function setExecutionDelay(uint256 _newExecutionDelay) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
// executionDelay does not have to be non-zero
executionDelay = _newExecutionDelay;
emit ExecutionDelayUpdated(_newExecutionDelay);
}
// ========================================= Guardian Actions =========================================
/**
* @notice Allows the guardianAddress to execute protocol actions
* @param _targetContractRegistryKey - key in registry of target contract
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function guardianExecuteTransaction(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData
) external
{
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
// _targetContractRegistryKey must point to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
_callValue,
_functionSignature,
_callData
);
require(success, "Governance: Transaction failed.");
emit GuardianTransactionExecuted(
targetContractAddress,
_callValue,
_functionSignature,
_callData,
returnData
);
}
/**
* @notice Change the guardian address
* @dev Only callable by current guardian
* @param _newGuardianAddress - new guardian address
*/
function transferGuardianship(address _newGuardianAddress) external {
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
guardianAddress = _newGuardianAddress;
emit GuardianshipTransferred(_newGuardianAddress);
}
// ========================================= Getter Functions =========================================
/**
* @notice Get proposal information by proposal Id
* @param _proposalId - id of proposal
*/
function getProposalById(uint256 _proposalId)
external view returns (
uint256 proposalId,
address proposer,
uint256 submissionBlockNumber,
bytes32 targetContractRegistryKey,
address targetContractAddress,
uint256 callValue,
string memory functionSignature,
bytes memory callData,
Outcome outcome,
uint256 voteMagnitudeYes,
uint256 voteMagnitudeNo,
uint256 numVotes
)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
Proposal memory proposal = proposals[_proposalId];
return (
proposal.proposalId,
proposal.proposer,
proposal.submissionBlockNumber,
proposal.targetContractRegistryKey,
proposal.targetContractAddress,
proposal.callValue,
proposal.functionSignature,
proposal.callData,
proposal.outcome,
proposal.voteMagnitudeYes,
proposal.voteMagnitudeNo,
proposal.numVotes
/** @notice - votes mapping cannot be returned by external function */
/** @notice - voteMagnitudes mapping cannot be returned by external function */
/** @notice - returning contractHash leads to stack too deep compiler error, see getProposalTargetContractHash() */
);
}
/**
* @notice Get proposal target contract hash by proposalId
* @dev This is a separate function because the getProposalById returns too many
variables already and by adding more, you get the error
`InternalCompilerError: Stack too deep, try using fewer variables`
* @param _proposalId - id of proposal
*/
function getProposalTargetContractHash(uint256 _proposalId)
external view returns (bytes32)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (proposals[_proposalId].contractHash);
}
/**
* @notice Get vote direction and vote magnitude for a given proposal and voter
* @param _proposalId - id of the proposal
* @param _voter - address of the voter we want to check
* @return returns vote direction and magnitude if valid vote, else default values
*/
function getVoteInfoByProposalAndVoter(uint256 _proposalId, address _voter)
external view returns (Vote vote, uint256 voteMagnitude)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (
proposals[_proposalId].votes[_voter],
proposals[_proposalId].voteMagnitudes[_voter]
);
}
/// @notice Get the contract Guardian address
function getGuardianAddress() external view returns (address) {
_requireIsInitialized();
return guardianAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the contract voting period
function getVotingPeriod() external view returns (uint256) {
_requireIsInitialized();
return votingPeriod;
}
/// @notice Get the contract voting quorum percent
function getVotingQuorumPercent() external view returns (uint256) {
_requireIsInitialized();
return votingQuorumPercent;
}
/// @notice Get the registry address
function getRegistryAddress() external view returns (address) {
_requireIsInitialized();
return address(registry);
}
/// @notice Used to check if is governance contract before setting governance address in other contracts
function isGovernanceAddress() external pure returns (bool) {
return true;
}
/// @notice Get the max number of concurrent InProgress proposals
function getMaxInProgressProposals() external view returns (uint16) {
_requireIsInitialized();
return maxInProgressProposals;
}
/// @notice Get the proposal execution delay
function getExecutionDelay() external view returns (uint256) {
_requireIsInitialized();
return executionDelay;
}
/// @notice Get the array of all InProgress proposal Ids
function getInProgressProposals() external view returns (uint256[] memory) {
_requireIsInitialized();
return inProgressProposals;
}
/**
* @notice Returns false if any proposals in inProgressProposals array are evaluatable
* Evaluatable = proposals with closed votingPeriod
* @dev Is public since its called internally in `submitProposal()` as well as externally in UI
*/
function inProgressProposalsAreUpToDate() external view returns (bool) {
_requireIsInitialized();
// compare current block number against endBlockNumber of each proposal
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (
block.number >
(proposals[inProgressProposals[i]].submissionBlockNumber).add(votingPeriod).add(executionDelay)
) {
return false;
}
}
return true;
}
// ========================================= Internal Functions =========================================
/**
* @notice Execute a transaction attached to a governance proposal
* @dev We are aware of both potential re-entrancy issues and the risks associated with low-level solidity
* function calls here, but have chosen to keep this code with those issues in mind. All governance
* proposals go through a voting process, and all will be reviewed carefully to ensure that they
* adhere to the expected behaviors of this call - but adding restrictions here would limit the ability
* of the governance system to do required work in a generic way.
* @param _targetContractAddress - address of registry proxy contract to execute transaction on
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function _executeTransaction(
address _targetContractAddress,
uint256 _callValue,
string memory _functionSignature,
bytes memory _callData
) internal returns (bool success, bytes memory returnData)
{
bytes memory encodedCallData = abi.encodePacked(
bytes4(keccak256(bytes(_functionSignature))),
_callData
);
(success, returnData) = (
// solium-disable-next-line security/no-call-value
_targetContractAddress.call.value(_callValue)(encodedCallData)
);
return (success, returnData);
}
function _increaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.add(_voterStake)
);
}
function _increaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.add(_voterStake)
);
}
function _decreaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.sub(_voterStake)
);
}
function _decreaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.sub(_voterStake)
);
}
/**
* @dev Can make O(1) by storing index pointer in proposals mapping.
* Requires inProgressProposals to be 1-indexed, since all proposals that are not present
* will have pointer set to 0.
*/
function _removeFromInProgressProposals(uint256 _proposalId) internal {
uint256 index = 0;
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (inProgressProposals[i] == _proposalId) {
index = i;
break;
}
}
// Swap proposalId to end of array + pop (deletes last elem + decrements array length)
inProgressProposals[index] = inProgressProposals[inProgressProposals.length - 1];
inProgressProposals.pop();
}
/**
* @notice Returns true if voting quorum percentage met for proposal, else false.
* @dev Quorum is met if total voteMagnitude * 100 / total active stake in Staking
* @dev Eventual multiplication overflow:
* (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo), with 100% staking participation,
* can sum to at most the entire token supply of 10^27
* With 7% annual token supply inflation, multiplication can overflow ~1635 years at the earliest:
* log(2^256/(10^27*100))/log(1.07) ~= 1635
*
* @dev Note that quorum is evaluated based on total staked at proposal submission
* not total staked at proposal evaluation, this is expected behavior
*/
function _quorumMet(Proposal memory proposal, Staking stakingContract)
internal view returns (bool)
{
uint256 participation = (
(proposal.voteMagnitudeYes + proposal.voteMagnitudeNo)
.mul(100)
.div(stakingContract.totalStakedAt(proposal.submissionBlockNumber))
);
return participation >= votingQuorumPercent;
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"Governance: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Governance: serviceProviderFactoryAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Governance: delegateManagerAddress is not set"
);
}
function _requireValidProposalId(uint256 _proposalId) private view {
require(
_proposalId <= lastProposalId && _proposalId > 0,
"Governance: Must provide valid non-zero _proposalId"
);
}
/**
* Calculates and returns active stake for address
*
* Active stake = (active deployer stake + active delegator stake)
* active deployer stake = (direct deployer stake - locked deployer stake)
* locked deployer stake = amount of pending decreaseStakeRequest for address
* active delegator stake = (total delegator stake - locked delegator stake)
* locked delegator stake = amount of pending undelegateRequest for address
*/
function _calculateAddressActiveStake(address _address) private view returns (uint256) {
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
DelegateManagerV2 delegateManager = DelegateManagerV2(delegateManagerAddress);
// Amount directly staked by address, if any, in ServiceProviderFactory
(uint256 directDeployerStake,,,,,) = spFactory.getServiceProviderDetails(_address);
// Amount of pending decreasedStakeRequest for address, if any, in ServiceProviderFactory
(uint256 lockedDeployerStake,) = spFactory.getPendingDecreaseStakeRequest(_address);
// active deployer stake = (direct deployer stake - locked deployer stake)
uint256 activeDeployerStake = directDeployerStake.sub(lockedDeployerStake);
// Total amount delegated by address, if any, in DelegateManager
uint256 totalDelegatorStake = delegateManager.getTotalDelegatorStake(_address);
// Amount of pending undelegateRequest for address, if any, in DelegateManager
(,uint256 lockedDelegatorStake, ) = delegateManager.getPendingUndelegateRequest(_address);
// active delegator stake = (total delegator stake - locked delegator stake)
uint256 activeDelegatorStake = totalDelegatorStake.sub(lockedDelegatorStake);
// activeStake = (activeDeployerStake + activeDelegatorStake)
uint256 activeStake = activeDeployerStake.add(activeDelegatorStake);
return activeStake;
}
// solium-disable security/no-inline-assembly
/**
* @notice Helper function to generate the code hash for a contract address
* @return contract code hash
*/
function _getCodeHash(address _contract) private view returns (bytes32) {
bytes32 contractHash;
assembly {
contractHash := extcodehash(_contract)
}
return contractHash;
}
}
// File: contracts/Staking.sol
pragma solidity ^0.5.0;
contract Staking is InitializableV2 {
using SafeMath for uint256;
using Uint256Helpers for uint256;
using Checkpointing for Checkpointing.History;
using SafeERC20 for ERC20;
string private constant ERROR_TOKEN_NOT_CONTRACT = "Staking: Staking token is not a contract";
string private constant ERROR_AMOUNT_ZERO = "Staking: Zero amount not allowed";
string private constant ERROR_ONLY_GOVERNANCE = "Staking: Only governance";
string private constant ERROR_ONLY_DELEGATE_MANAGER = (
"Staking: Only callable from DelegateManager"
);
string private constant ERROR_ONLY_SERVICE_PROVIDER_FACTORY = (
"Staking: Only callable from ServiceProviderFactory"
);
address private governanceAddress;
address private claimsManagerAddress;
address private delegateManagerAddress;
address private serviceProviderFactoryAddress;
/// @dev stores the history of staking and claims for a given address
struct Account {
Checkpointing.History stakedHistory;
Checkpointing.History claimHistory;
}
/// @dev ERC-20 token that will be used to stake with
ERC20 internal stakingToken;
/// @dev maps addresses to staking and claims history
mapping (address => Account) internal accounts;
/// @dev total staked tokens at a given block
Checkpointing.History internal totalStakedHistory;
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event Slashed(address indexed user, uint256 amount, uint256 total);
/**
* @notice Function to initialize the contract
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @param _tokenAddress - address of ERC20 token that will be staked
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT);
stakingToken = ERC20(_tokenAddress);
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
/**
* @notice Set the ClaimsManaager address
* @dev Only callable by Governance address
* @param _claimsManager - address for new ClaimsManaager contract
*/
function setClaimsManagerAddress(address _claimsManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManager;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManager - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManager;
}
/* External functions */
/**
* @notice Funds `_amount` of tokens from ClaimsManager to target account
* @param _amount - amount of rewards to add to stake
* @param _stakerAccount - address of staker
*/
function stakeRewards(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress,
"Staking: Only callable from ClaimsManager"
);
_stakeFor(_stakerAccount, msg.sender, _amount);
this.updateClaimHistory(_amount, _stakerAccount);
}
/**
* @notice Update claim history by adding an event to the claim history
* @param _amount - amount to add to claim history
* @param _stakerAccount - address of staker
*/
function updateClaimHistory(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress || msg.sender == address(this),
"Staking: Only callable from ClaimsManager or Staking.sol"
);
// Update claim history even if no value claimed
accounts[_stakerAccount].claimHistory.add(block.number.toUint64(), _amount);
}
/**
* @notice Slashes `_amount` tokens from _slashAddress
* @dev Callable from DelegateManager
* @param _amount - Number of tokens slashed
* @param _slashAddress - Address being slashed
*/
function slash(
uint256 _amount,
address _slashAddress
) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
// Burn slashed tokens from account
_burnFor(_slashAddress, _amount);
emit Slashed(
_slashAddress,
_amount,
totalStakedFor(_slashAddress)
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from _accountAddress, and assigns them to `_accountAddress`
* @param _accountAddress - The final staker of the tokens
* @param _amount - Number of tokens staked
*/
function stakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_stakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the desired account.
* @param _accountAddress - Account unstaked for, and token recipient
* @param _amount - Number of tokens staked
*/
function unstakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_unstakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from `_delegatorAddress` to `_accountAddress`,
only callable by DelegateManager
* @param _accountAddress - The final staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens staked
*/
function delegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_stakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Unstakes '_amount` tokens, transferring them from `_accountAddress` to `_delegatorAddress`,
only callable by DelegateManager
* @param _accountAddress - The staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens unstaked
*/
function undelegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_unstakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Get the token used by the contract for staking and locking
* @return The token used by the contract for staking and locking
*/
function token() external view returns (address) {
_requireIsInitialized();
return address(stakingToken);
}
/**
* @notice Check whether it supports history of stakes
* @return Always true
*/
function supportsHistory() external view returns (bool) {
_requireIsInitialized();
return true;
}
/**
* @notice Get last time `_accountAddress` modified its staked balance
* @param _accountAddress - Account requesting for
* @return Last block number when account's balance was modified
*/
function lastStakedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].stakedHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].stakedHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get last time `_accountAddress` claimed a staking reward
* @param _accountAddress - Account requesting for
* @return Last block number when claim requested
*/
function lastClaimedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].claimHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].claimHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber`
* @param _accountAddress - Account requesting for
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked by the account at the given block number
*/
function totalStakedForAt(
address _accountAddress,
uint256 _blockNumber
) external view returns (uint256) {
_requireIsInitialized();
return accounts[_accountAddress].stakedHistory.get(_blockNumber.toUint64());
}
/**
* @notice Get the total amount of tokens staked by all users at block number `_blockNumber`
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked at the given block number
*/
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
_requireIsInitialized();
return totalStakedHistory.get(_blockNumber.toUint64());
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Helper function wrapped around totalStakedFor. Checks whether _accountAddress
is currently a valid staker with a non-zero stake
* @param _accountAddress - Account requesting for
* @return Boolean indicating whether account is a staker
*/
function isStaker(address _accountAddress) external view returns (bool) {
_requireIsInitialized();
return totalStakedFor(_accountAddress) > 0;
}
/* Public functions */
/**
* @notice Get the amount of tokens staked by `_accountAddress`
* @param _accountAddress - The owner of the tokens
* @return The amount of tokens staked by the given account
*/
function totalStakedFor(address _accountAddress) public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return accounts[_accountAddress].stakedHistory.getLast();
}
/**
* @notice Get the total amount of tokens staked by all users
* @return The total amount of tokens staked by all users
*/
function totalStaked() public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return totalStakedHistory.getLast();
}
// ========================================= Internal Functions =========================================
/**
* @notice Adds stake from a transfer account to the stake account
* @param _stakeAccount - Account that funds will be staked for
* @param _transferAccount - Account that funds will be transferred from
* @param _amount - amount to stake
*/
function _stakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
// staking 0 tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// Checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, true);
// checkpoint total supply
_modifyTotalStaked(_amount, true);
// pull tokens into Staking contract
stakingToken.safeTransferFrom(_transferAccount, address(this), _amount);
emit Staked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount));
}
/**
* @notice Unstakes tokens from a stake account to a transfer account
* @param _stakeAccount - Account that staked funds will be transferred from
* @param _transferAccount - Account that funds will be transferred to
* @param _amount - amount to unstake
*/
function _unstakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(_transferAccount, _amount);
emit Unstaked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount)
);
}
/**
* @notice Burn tokens for a given staker
* @dev Called when slash occurs
* @param _stakeAccount - Account for which funds will be burned
* @param _amount - amount to burn
*/
function _burnFor(address _stakeAccount, uint256 _amount) internal {
// burning zero tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// burn
ERC20Burnable(address(stakingToken)).burn(_amount);
/** No event emitted since token.burn() call already emits a Transfer event */
}
/**
* @notice Increase or decrease the staked balance for an account
* @param _accountAddress - Account to modify
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal {
uint256 currentInternalStake = accounts[_accountAddress].stakedHistory.getLast();
uint256 newStake;
if (_increase) {
newStake = currentInternalStake.add(_by);
} else {
require(
currentInternalStake >= _by,
"Staking: Cannot decrease greater than current balance");
newStake = currentInternalStake.sub(_by);
}
// add new value to account history
accounts[_accountAddress].stakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Increase or decrease the staked balance across all accounts
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyTotalStaked(uint256 _by, bool _increase) internal {
uint256 currentStake = totalStaked();
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// add new value to total history
totalStakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"Staking: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
// ========================================= Private Functions =========================================
function _requireClaimsManagerAddressIsSet() private view {
require(claimsManagerAddress != address(0x00), "Staking: claimsManagerAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Staking: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Staking: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceTypeManager.sol
pragma solidity ^0.5.0;
contract ServiceTypeManager is InitializableV2 {
address governanceAddress;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceTypeManager: Only callable by Governance contract"
);
/**
* @dev - mapping of serviceType - serviceTypeVersion
* Example - "discovery-provider" - ["0.0.1", "0.0.2", ..., "currentVersion"]
*/
mapping(bytes32 => bytes32[]) private serviceTypeVersions;
/**
* @dev - mapping of serviceType - < serviceTypeVersion, isValid >
* Example - "discovery-provider" - <"0.0.1", true>
*/
mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo;
/// @dev List of valid service types
bytes32[] private validServiceTypes;
/// @dev Struct representing service type info
struct ServiceTypeInfo {
bool isValid;
uint256 minStake;
uint256 maxStake;
}
/// @dev mapping of service type info
mapping(bytes32 => ServiceTypeInfo) private serviceTypeInfo;
event SetServiceVersion(
bytes32 indexed _serviceType,
bytes32 indexed _serviceVersion
);
event ServiceTypeAdded(
bytes32 indexed _serviceType,
uint256 indexed _serviceTypeMin,
uint256 indexed _serviceTypeMax
);
event ServiceTypeRemoved(bytes32 indexed _serviceType);
/**
* @notice Function to initialize the contract
* @param _governanceAddress - Governance proxy address
*/
function initialize(address _governanceAddress) public initializer
{
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
// ========================================= Service Type Logic =========================================
/**
* @notice Add a new service type
* @param _serviceType - type of service to add
* @param _serviceTypeMin - minimum stake for service type
* @param _serviceTypeMax - maximum stake for service type
*/
function addServiceType(
bytes32 _serviceType,
uint256 _serviceTypeMin,
uint256 _serviceTypeMax
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(
!this.serviceTypeIsValid(_serviceType),
"ServiceTypeManager: Already known service type"
);
require(
_serviceTypeMax > _serviceTypeMin,
"ServiceTypeManager: Max stake must be non-zero and greater than min stake"
);
// Ensure serviceType cannot be re-added if it previously existed and was removed
// stored maxStake > 0 means it was previously added and removed
require(
serviceTypeInfo[_serviceType].maxStake == 0,
"ServiceTypeManager: Cannot re-add serviceType after it was removed."
);
validServiceTypes.push(_serviceType);
serviceTypeInfo[_serviceType] = ServiceTypeInfo({
isValid: true,
minStake: _serviceTypeMin,
maxStake: _serviceTypeMax
});
emit ServiceTypeAdded(_serviceType, _serviceTypeMin, _serviceTypeMax);
}
/**
* @notice Remove an existing service type
* @param _serviceType - name of service type to remove
*/
function removeServiceType(bytes32 _serviceType) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
uint256 serviceIndex = 0;
bool foundService = false;
for (uint256 i = 0; i < validServiceTypes.length; i ++) {
if (validServiceTypes[i] == _serviceType) {
serviceIndex = i;
foundService = true;
break;
}
}
require(foundService == true, "ServiceTypeManager: Invalid service type, not found");
// Overwrite service index
uint256 lastIndex = validServiceTypes.length - 1;
validServiceTypes[serviceIndex] = validServiceTypes[lastIndex];
validServiceTypes.length--;
// Mark as invalid
serviceTypeInfo[_serviceType].isValid = false;
// Note - stake bounds are not reset so they can be checked to prevent serviceType from being re-added
emit ServiceTypeRemoved(_serviceType);
}
/**
* @notice Get isValid, min and max stake for a given service type
* @param _serviceType - type of service
* @return isValid, min and max stake for type
*/
function getServiceTypeInfo(bytes32 _serviceType)
external view returns (bool isValid, uint256 minStake, uint256 maxStake)
{
_requireIsInitialized();
return (
serviceTypeInfo[_serviceType].isValid,
serviceTypeInfo[_serviceType].minStake,
serviceTypeInfo[_serviceType].maxStake
);
}
/**
* @notice Get list of valid service types
*/
function getValidServiceTypes()
external view returns (bytes32[] memory)
{
_requireIsInitialized();
return validServiceTypes;
}
/**
* @notice Return indicating whether this is a valid service type
*/
function serviceTypeIsValid(bytes32 _serviceType)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeInfo[_serviceType].isValid;
}
// ========================================= Service Version Logic =========================================
/**
* @notice Add new version for a serviceType
* @param _serviceType - type of service
* @param _serviceVersion - new version of service to add
*/
function setServiceVersion(
bytes32 _serviceType,
bytes32 _serviceVersion
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Invalid service type");
require(
serviceTypeVersionInfo[_serviceType][_serviceVersion] == false,
"ServiceTypeManager: Already registered"
);
// Update array of known versions for type
serviceTypeVersions[_serviceType].push(_serviceVersion);
// Update status for this specific service version
serviceTypeVersionInfo[_serviceType][_serviceVersion] = true;
emit SetServiceVersion(_serviceType, _serviceVersion);
}
/**
* @notice Get a version for a service type given it's index
* @param _serviceType - type of service
* @param _versionIndex - index in list of service versions
* @return bytes32 value for serviceVersion
*/
function getVersion(bytes32 _serviceType, uint256 _versionIndex)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length > _versionIndex,
"ServiceTypeManager: No registered version of serviceType"
);
return (serviceTypeVersions[_serviceType][_versionIndex]);
}
/**
* @notice Get curent version for a service type
* @param _serviceType - type of service
* @return Returns current version of service
*/
function getCurrentVersion(bytes32 _serviceType)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length >= 1,
"ServiceTypeManager: No registered version of serviceType"
);
uint256 latestVersionIndex = serviceTypeVersions[_serviceType].length - 1;
return (serviceTypeVersions[_serviceType][latestVersionIndex]);
}
/**
* @notice Get total number of versions for a service type
* @param _serviceType - type of service
*/
function getNumberOfVersions(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceTypeVersions[_serviceType].length;
}
/**
* @notice Return boolean indicating whether given version is valid for given type
* @param _serviceType - type of service
* @param _serviceVersion - version of service to check
*/
function serviceVersionIsValid(bytes32 _serviceType, bytes32 _serviceVersion)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeVersionInfo[_serviceType][_serviceVersion];
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceTypeManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
}
// File: contracts/ClaimsManager.sol
pragma solidity ^0.5.0;
/// @notice ERC20 imported via Staking.sol
/// @notice SafeERC20 imported via Staking.sol
/// @notice Governance imported via Staking.sol
/// @notice SafeMath imported via ServiceProviderFactory.sol
/**
* Designed to automate claim funding, minting tokens as necessary
* @notice - will call InitializableV2 constructor
*/
contract ClaimsManager is InitializableV2 {
using SafeMath for uint256;
using SafeERC20 for ERC20;
string private constant ERROR_ONLY_GOVERNANCE = (
"ClaimsManager: Only callable by Governance contract"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private delegateManagerAddress;
/**
* @notice - Minimum number of blocks between funding rounds
* 604800 seconds / week
* Avg block time - 13s
* 604800 / 13 = 46523.0769231 blocks
*/
uint256 private fundingRoundBlockDiff;
/**
* @notice - Configures the current funding amount per round
* Weekly rounds, 7% PA inflation = 70,000,000 new tokens in first year
* = 70,000,000/365*7 (year is slightly more than a week)
* = 1342465.75342 new AUDS per week
* = 1342465753420000000000000 new wei units per week
* @dev - Past a certain block height, this schedule will be updated
* - Logic determining schedule will be sourced from an external contract
*/
uint256 private fundingAmount;
// Denotes current round
uint256 private roundNumber;
// Staking contract ref
ERC20Mintable private audiusToken;
/// @dev - Address to which recurringCommunityFundingAmount is transferred at funding round start
address private communityPoolAddress;
/// @dev - Reward amount transferred to communityPoolAddress at funding round start
uint256 private recurringCommunityFundingAmount;
// Struct representing round state
// 1) Block at which round was funded
// 2) Total funded for this round
// 3) Total claimed in round
struct Round {
uint256 fundedBlock;
uint256 fundedAmount;
uint256 totalClaimedInRound;
}
// Current round information
Round private currentRound;
event RoundInitiated(
uint256 indexed _blockNumber,
uint256 indexed _roundNumber,
uint256 indexed _fundAmount
);
event ClaimProcessed(
address indexed _claimer,
uint256 indexed _rewards,
uint256 _oldTotal,
uint256 indexed _newTotal
);
event CommunityRewardsTransferred(
address indexed _transferAddress,
uint256 indexed _amount
);
event FundingAmountUpdated(uint256 indexed _amount);
event FundingRoundBlockDiffUpdated(uint256 indexed _blockDifference);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event RecurringCommunityFundingAmountUpdated(uint256 indexed _amount);
event CommunityPoolAddressUpdated(address indexed _newCommunityPoolAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
fundingRoundBlockDiff = 46523;
fundingAmount = 1342465753420000000000000; // 1342465.75342 AUDS
roundNumber = 0;
currentRound = Round({
fundedBlock: 0,
fundedAmount: 0,
totalClaimedInRound: 0
});
// Community pool funding amount and address initialized to zero
recurringCommunityFundingAmount = 0;
communityPoolAddress = address(0x0);
InitializableV2.initialize();
}
/// @notice Get the duration of a funding round in blocks
function getFundingRoundBlockDiff() external view returns (uint256)
{
_requireIsInitialized();
return fundingRoundBlockDiff;
}
/// @notice Get the last block where a funding round was initiated
function getLastFundedBlock() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.fundedBlock;
}
/// @notice Get the amount funded per round in wei
function getFundsPerRound() external view returns (uint256)
{
_requireIsInitialized();
return fundingAmount;
}
/// @notice Get the total amount claimed in the current round
function getTotalClaimedInRound() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.totalClaimedInRound;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Get the Staking address
*/
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
/**
* @notice Get the community pool address
*/
function getCommunityPoolAddress() external view returns (address)
{
_requireIsInitialized();
return communityPoolAddress;
}
/**
* @notice Get the community funding amount
*/
function getRecurringCommunityFundingAmount() external view returns (uint256)
{
_requireIsInitialized();
return recurringCommunityFundingAmount;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
emit ServiceProviderFactoryAddressUpdated(_serviceProviderFactoryAddress);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManagerAddress;
emit DelegateManagerAddressUpdated(_delegateManagerAddress);
}
/**
* @notice Start a new funding round
* @dev Permissioned to be callable by stakers or governance contract
*/
function initiateRound() external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
block.number.sub(currentRound.fundedBlock) > fundingRoundBlockDiff,
"ClaimsManager: Required block difference not met"
);
currentRound = Round({
fundedBlock: block.number,
fundedAmount: fundingAmount,
totalClaimedInRound: 0
});
roundNumber = roundNumber.add(1);
/*
* Transfer community funding amount to community pool address, if set
*/
if (recurringCommunityFundingAmount > 0 && communityPoolAddress != address(0x0)) {
// ERC20Mintable always returns true
audiusToken.mint(address(this), recurringCommunityFundingAmount);
// Approve transfer to community pool address
audiusToken.approve(communityPoolAddress, recurringCommunityFundingAmount);
// Transfer to community pool address
ERC20(address(audiusToken)).safeTransfer(communityPoolAddress, recurringCommunityFundingAmount);
emit CommunityRewardsTransferred(communityPoolAddress, recurringCommunityFundingAmount);
}
emit RoundInitiated(
currentRound.fundedBlock,
roundNumber,
currentRound.fundedAmount
);
}
/**
* @notice Mints and stakes tokens on behalf of ServiceProvider + delegators
* @dev Callable through DelegateManager by Service Provider
* @param _claimer - service provider address
* @param _totalLockedForSP - amount of tokens locked up across DelegateManager + ServiceProvider
* @return minted rewards for this claimer
*/
function processClaim(
address _claimer,
uint256 _totalLockedForSP
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ClaimsManager: ProcessClaim only accessible to DelegateManager"
);
Staking stakingContract = Staking(stakingAddress);
// Prevent duplicate claim
uint256 lastUserClaimBlock = stakingContract.lastClaimedFor(_claimer);
require(
lastUserClaimBlock <= currentRound.fundedBlock,
"ClaimsManager: Claim already processed for user"
);
uint256 totalStakedAtFundBlockForClaimer = stakingContract.totalStakedForAt(
_claimer,
currentRound.fundedBlock);
(,,bool withinBounds,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_claimer)
);
// Once they claim the zero reward amount, stake can be modified once again
// Subtract total locked amount for SP from stake at fund block
uint256 totalActiveClaimerStake = totalStakedAtFundBlockForClaimer.sub(_totalLockedForSP);
uint256 totalStakedAtFundBlock = stakingContract.totalStakedAt(currentRound.fundedBlock);
// Calculate claimer rewards
uint256 rewardsForClaimer = (
totalActiveClaimerStake.mul(fundingAmount)
).div(totalStakedAtFundBlock);
// For a claimer violating bounds, no new tokens are minted
// Claim history is marked to zero and function is short-circuited
// Total rewards can be zero if all stake is currently locked up
if (!withinBounds || rewardsForClaimer == 0) {
stakingContract.updateClaimHistory(0, _claimer);
emit ClaimProcessed(
_claimer,
0,
totalStakedAtFundBlockForClaimer,
totalActiveClaimerStake
);
return 0;
}
// ERC20Mintable always returns true
audiusToken.mint(address(this), rewardsForClaimer);
// Approve transfer to staking address for claimer rewards
// ERC20 always returns true
audiusToken.approve(stakingAddress, rewardsForClaimer);
// Transfer rewards
stakingContract.stakeRewards(rewardsForClaimer, _claimer);
// Update round claim value
currentRound.totalClaimedInRound = currentRound.totalClaimedInRound.add(rewardsForClaimer);
// Update round claim value
uint256 newTotal = stakingContract.totalStakedFor(_claimer);
emit ClaimProcessed(
_claimer,
rewardsForClaimer,
totalStakedAtFundBlockForClaimer,
newTotal
);
return rewardsForClaimer;
}
/**
* @notice Modify funding amount per round
* @param _newAmount - new amount to fund per round in wei
*/
function updateFundingAmount(uint256 _newAmount) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
fundingAmount = _newAmount;
emit FundingAmountUpdated(_newAmount);
}
/**
* @notice Returns boolean indicating whether a claim is considered pending
* @dev Note that an address with no endpoints can never have a pending claim
* @param _sp - address of the service provider to check
* @return true if eligible for claim, false if not
*/
function claimPending(address _sp) external view returns (bool) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
uint256 lastClaimedForSP = Staking(stakingAddress).lastClaimedFor(_sp);
(,,,uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_sp)
);
return (lastClaimedForSP < currentRound.fundedBlock && numEndpoints > 0);
}
/**
* @notice Modify minimum block difference between funding rounds
* @param _newFundingRoundBlockDiff - new min block difference to set
*/
function updateFundingRoundBlockDiff(uint256 _newFundingRoundBlockDiff) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
emit FundingRoundBlockDiffUpdated(_newFundingRoundBlockDiff);
fundingRoundBlockDiff = _newFundingRoundBlockDiff;
}
/**
* @notice Modify community funding amound for each round
* @param _newRecurringCommunityFundingAmount - new reward amount transferred to
* communityPoolAddress at funding round start
*/
function updateRecurringCommunityFundingAmount(
uint256 _newRecurringCommunityFundingAmount
) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
recurringCommunityFundingAmount = _newRecurringCommunityFundingAmount;
emit RecurringCommunityFundingAmountUpdated(_newRecurringCommunityFundingAmount);
}
/**
* @notice Modify community pool address
* @param _newCommunityPoolAddress - new address to which recurringCommunityFundingAmount
* is transferred at funding round start
*/
function updateCommunityPoolAddress(address _newCommunityPoolAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
communityPoolAddress = _newCommunityPoolAddress;
emit CommunityPoolAddressUpdated(_newCommunityPoolAddress);
}
// ========================================= Private Functions =========================================
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) private {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ClaimsManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
function _requireStakingAddressIsSet() private view {
require(stakingAddress != address(0x00), "ClaimsManager: stakingAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ClaimsManager: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"ClaimsManager: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceProviderFactory.sol
pragma solidity ^0.5.0;
/// @notice Governance imported via Staking.sol
contract ServiceProviderFactory is InitializableV2 {
using SafeMath for uint256;
/// @dev - denominator for deployer cut calculations
/// @dev - user values are intended to be x/DEPLOYER_CUT_BASE
uint256 private constant DEPLOYER_CUT_BASE = 100;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Governance contract"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Service Provider or Governance"
);
address private stakingAddress;
address private delegateManagerAddress;
address private governanceAddress;
address private serviceTypeManagerAddress;
address private claimsManagerAddress;
/// @notice Period in blocks that a decrease stake operation is delayed.
/// Must be greater than governance votingPeriod + executionDelay in order to
/// prevent pre-emptive withdrawal in anticipation of a slash proposal
uint256 private decreaseStakeLockupDuration;
/// @notice Period in blocks that an update deployer cut operation is delayed.
/// Must be greater than funding round block diff in order
/// to prevent manipulation around a funding round
uint256 private deployerCutLockupDuration;
/// @dev - Stores following entities
/// 1) Directly staked amount by SP, not including delegators
/// 2) % Cut of delegator tokens taken during reward
/// 3) Bool indicating whether this SP has met min/max requirements
/// 4) Number of endpoints registered by SP
/// 5) Minimum deployer stake for this service provider
/// 6) Maximum total stake for this account
struct ServiceProviderDetails {
uint256 deployerStake;
uint256 deployerCut;
bool validBounds;
uint256 numberOfEndpoints;
uint256 minAccountStake;
uint256 maxAccountStake;
}
/// @dev - Data structure for time delay during withdrawal
struct DecreaseStakeRequest {
uint256 decreaseAmount;
uint256 lockupExpiryBlock;
}
/// @dev - Data structure for time delay during deployer cut update
struct UpdateDeployerCutRequest {
uint256 newDeployerCut;
uint256 lockupExpiryBlock;
}
/// @dev - Struct maintaining information about sp
/// @dev - blocknumber is block.number when endpoint registered
struct ServiceEndpoint {
address owner;
string endpoint;
uint256 blocknumber;
address delegateOwnerWallet;
}
/// @dev - Mapping of service provider address to details
mapping(address => ServiceProviderDetails) private spDetails;
/// @dev - Uniquely assigned serviceProvider ID, incremented for each service type
/// @notice - Keeps track of the total number of services registered regardless of
/// whether some have been deregistered since
mapping(bytes32 => uint256) private serviceProviderTypeIDs;
/// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo))
/// @notice - stores the actual service provider data like endpoint and owner wallet
/// with the ability lookup by service type and service id */
mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo;
/// @dev - mapping of keccak256(endpoint) to uint256 ID
/// @notice - used to check if a endpoint has already been registered and also lookup
/// the id of an endpoint
mapping(bytes32 => uint256) private serviceProviderEndpointToId;
/// @dev - mapping of address -> sp id array */
/// @notice - stores all the services registered by a provider. for each address,
/// provides the ability to lookup by service type and see all registered services
mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId;
/// @dev - Mapping of service provider -> decrease stake request
mapping(address => DecreaseStakeRequest) private decreaseStakeRequests;
/// @dev - Mapping of service provider -> update deployer cut requests
mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests;
event RegisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _stakeAmount
);
event DeregisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _unstakeAmount
);
event IncreasedStake(
address indexed _owner,
uint256 indexed _increaseAmount,
uint256 indexed _newStakeAmount
);
event DecreaseStakeRequested(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestCancelled(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestEvaluated(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _newStakeAmount
);
event EndpointUpdated(
bytes32 indexed _serviceType,
address indexed _owner,
string _oldEndpoint,
string _newEndpoint,
uint256 indexed _spID
);
event DelegateOwnerWalletUpdated(
address indexed _owner,
bytes32 indexed _serviceType,
uint256 indexed _spID,
address _updatedWallet
);
event DeployerCutUpdateRequested(
address indexed _owner,
uint256 indexed _updatedCut,
uint256 indexed _lockupExpiryBlock
);
event DeployerCutUpdateRequestCancelled(
address indexed _owner,
uint256 indexed _requestedCut,
uint256 indexed _finalCut
);
event DeployerCutUpdateRequestEvaluated(
address indexed _owner,
uint256 indexed _updatedCut
);
event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration);
event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _governanceAddress,
address _claimsManagerAddress,
uint256 _decreaseStakeLockupDuration,
uint256 _deployerCutLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
claimsManagerAddress = _claimsManagerAddress;
_updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration);
_updateDeployerCutLockupDuration(_deployerCutLockupDuration);
InitializableV2.initialize();
}
/**
* @notice Register a new endpoint to the account of msg.sender
* @dev Transfers stake from service provider into staking pool
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager
* @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties
* @return New service provider ID for this endpoint
*/
function register(
bytes32 _serviceType,
string calldata _endpoint,
uint256 _stakeAmount,
address _delegateOwnerWallet
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType),
"ServiceProviderFactory: Valid service type required");
// Stake token amount from msg.sender
if (_stakeAmount > 0) {
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No pending claim expected"
);
Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount);
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0,
"ServiceProviderFactory: Endpoint already registered");
uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1);
serviceProviderTypeIDs[_serviceType] = newServiceProviderID;
// Index spInfo
serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({
owner: msg.sender,
endpoint: _endpoint,
blocknumber: block.number,
delegateOwnerWallet: _delegateOwnerWallet
});
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
// Update (address -> type -> ids[])
serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID);
// Increment number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_stakeAmount)
);
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit RegisteredServiceProvider(
newServiceProviderID,
_serviceType,
msg.sender,
_endpoint,
currentlyStakedForOwner
);
return newServiceProviderID;
}
/**
* @notice Deregister an endpoint from the account of msg.sender
* @dev Unstakes all tokens for service provider if this is the last endpoint
* @param _serviceType - type of service to deregister
* @param _endpoint - endpoint to deregister
* @return spId of the service that was deregistered
*/
function deregister(
bytes32 _serviceType,
string calldata _endpoint
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
// Unstake on deregistration if and only if this is the last service endpoint
uint256 unstakeAmount = 0;
bool unstaked = false;
// owned by the service provider
if (spDetails[msg.sender].numberOfEndpoints == 1) {
unstakeAmount = spDetails[msg.sender].deployerStake;
// Submit request to decrease stake, overriding any pending request
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: unstakeAmount,
lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration)
});
unstaked = true;
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0,
"ServiceProviderFactory: Endpoint not registered");
// Cache invalided service provider ID
uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0;
require(
keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)),
"ServiceProviderFactory: Invalid endpoint for service type");
require (
serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender,
"ServiceProviderFactory: Only callable by endpoint owner");
// Update info mapping
delete serviceProviderInfo[_serviceType][deregisteredID];
// Reset id, update array
uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length;
for (uint256 i = 0; i < spTypeLength; i ++) {
if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) {
// Overwrite element to be deleted with last element in array
serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1];
// Reduce array size, exit loop
serviceProviderAddressToId[msg.sender][_serviceType].length--;
// Confirm this ID has been found for the service provider
break;
}
}
// Decrement number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints -= 1;
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax);
emit DeregisteredServiceProvider(
deregisteredID,
_serviceType,
msg.sender,
_endpoint,
unstakeAmount);
// Confirm both aggregate account balance and directly staked amount are valid
// Only if unstake operation has not occurred
if (!unstaked) {
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
}
return deregisteredID;
}
/**
* @notice Increase stake for service provider
* @param _increaseStakeAmount - amount to increase staked amount by
* @return New total stake for service provider
*/
function increaseStake(
uint256 _increaseStakeAmount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
// Confirm owner has an endpoint
require(
spDetails[msg.sender].numberOfEndpoints > 0,
"ServiceProviderFactory: Registered endpoint required to increase stake"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
// Stake increased token amount for msg.sender
stakingContract.stakeFor(msg.sender, _increaseStakeAmount);
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_increaseStakeAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit IncreasedStake(
msg.sender,
_increaseStakeAmount,
newStakeAmount
);
return newStakeAmount;
}
/**
* @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after
which the actual decreaseStake can be called
* @dev Decreasing stake is only processed if a service provider is within valid bounds
* @param _decreaseStakeAmount - amount to decrease stake by in wei
* @return New total stake amount after the lockup
*/
function requestDecreaseStake(uint256 _decreaseStakeAmount)
external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
_decreaseStakeAmount > 0,
"ServiceProviderFactory: Requested stake decrease amount must be greater than zero"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Prohibit decreasing stake to invalid bounds
_validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount)));
uint256 expiryBlock = block.number.add(decreaseStakeLockupDuration);
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: _decreaseStakeAmount,
lockupExpiryBlock: expiryBlock
});
emit DecreaseStakeRequested(msg.sender, _decreaseStakeAmount, expiryBlock);
return currentStakeAmount.sub(_decreaseStakeAmount);
}
/**
* @notice Cancel a decrease stake request during the lockup
* @dev Either called by the service provider via DelegateManager or governance
during a slash action
* @param _account - address of service provider
*/
function cancelDecreaseStakeRequest(address _account) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == _account || msg.sender == delegateManagerAddress,
"ServiceProviderFactory: Only owner or DelegateManager"
);
require(
_decreaseRequestIsPending(_account),
"ServiceProviderFactory: Decrease stake request must be pending"
);
DecreaseStakeRequest memory cancelledRequest = decreaseStakeRequests[_account];
// Clear decrease stake request
decreaseStakeRequests[_account] = DecreaseStakeRequest({
decreaseAmount: 0,
lockupExpiryBlock: 0
});
emit DecreaseStakeRequestCancelled(
_account,
cancelledRequest.decreaseAmount,
cancelledRequest.lockupExpiryBlock
);
}
/**
* @notice Called by user to decrease a stake after waiting the appropriate lockup period.
* @return New total stake after decrease
*/
function decreaseStake() external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
_decreaseRequestIsPending(msg.sender),
"ServiceProviderFactory: Decrease stake request must be pending"
);
require(
decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 decreaseAmount = decreaseStakeRequests[msg.sender].decreaseAmount;
// Decrease staked token amount for msg.sender
stakingContract.unstakeFor(msg.sender, decreaseAmount);
// Query current stake
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.sub(decreaseAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
// During registration this validation is bypassed since no endpoints remain
if (spDetails[msg.sender].numberOfEndpoints > 0) {
this.validateAccountStakeBalance(msg.sender);
}
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
// Clear decrease stake request
delete decreaseStakeRequests[msg.sender];
emit DecreaseStakeRequestEvaluated(msg.sender, decreaseAmount, newStakeAmount);
return newStakeAmount;
}
/**
* @notice Update delegate owner wallet for a given endpoint
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _updatedDelegateOwnerWallet - address of new delegate wallet
*/
function updateDelegateOwnerWallet(
bytes32 _serviceType,
string calldata _endpoint,
address _updatedDelegateOwnerWallet
) external
{
_requireIsInitialized();
uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint);
require(
serviceProviderInfo[_serviceType][spID].owner == msg.sender,
"ServiceProviderFactory: Invalid update operation, wrong owner"
);
serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet;
emit DelegateOwnerWalletUpdated(
msg.sender,
_serviceType,
spID,
_updatedDelegateOwnerWallet
);
}
/**
* @notice Update the endpoint for a given service
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _oldEndpoint - old endpoint currently registered
* @param _newEndpoint - new endpoint to replace old endpoint
* @return ID of updated service provider
*/
function updateEndpoint(
bytes32 _serviceType,
string calldata _oldEndpoint,
string calldata _newEndpoint
) external returns (uint256)
{
_requireIsInitialized();
uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint);
require (
spId != 0,
"ServiceProviderFactory: Could not find service provider with that endpoint"
);
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId];
require(
serviceEndpoint.owner == msg.sender,
"ServiceProviderFactory: Invalid update endpoint operation, wrong owner"
);
require(
keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)),
"ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider"
);
// invalidate old endpoint
serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0;
// update to new endpoint
serviceEndpoint.endpoint = _newEndpoint;
serviceProviderInfo[_serviceType][spId] = serviceEndpoint;
serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId;
emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId);
return spId;
}
/**
* @notice Update the deployer cut for a given service provider
* @param _serviceProvider - address of service provider
* @param _cut - new value for deployer cut
*/
function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external
{
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) &&
(updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0),
"ServiceProviderFactory: Update deployer cut operation pending"
);
require(
_cut <= DEPLOYER_CUT_BASE,
"ServiceProviderFactory: Service Provider cut cannot exceed base value"
);
uint256 expiryBlock = block.number + deployerCutLockupDuration;
updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({
lockupExpiryBlock: expiryBlock,
newDeployerCut: _cut
});
emit DeployerCutUpdateRequested(_serviceProvider, _cut, expiryBlock);
}
/**
* @notice Cancel a pending request to update deployer cut
* @param _serviceProvider - address of service provider
*/
function cancelUpdateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
UpdateDeployerCutRequest memory cancelledRequest = (
updateDeployerCutRequests[_serviceProvider]
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestCancelled(
_serviceProvider,
cancelledRequest.newDeployerCut,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Evalue request to update service provider cut of claims
* @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase.
* @dev SPs will interact with this value as a percent, value translation done client side
@dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round.
*/
function updateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
spDetails[_serviceProvider].deployerCut = (
updateDeployerCutRequests[_serviceProvider].newDeployerCut
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestEvaluated(
_serviceProvider,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Update service provider balance
* @dev Called by DelegateManager by functions modifying entire stake like claim and slash
* @param _serviceProvider - address of service provider
* @param _amount - new amount of direct state for service provider
*/
function updateServiceProviderStake(
address _serviceProvider,
uint256 _amount
) external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ServiceProviderFactory: only callable by DelegateManager"
);
// Update SP tracked total
spDetails[_serviceProvider].deployerStake = _amount;
_updateServiceProviderBoundStatus(_serviceProvider);
}
/// @notice Update service provider lockup duration
function updateDecreaseStakeLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDecreaseStakeLockupDuration(_duration);
emit DecreaseStakeLockupDurationUpdated(_duration);
}
/// @notice Update service provider lockup duration
function updateDeployerCutLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDeployerCutLockupDuration(_duration);
emit UpdateDeployerCutLockupDurationUpdated(_duration);
}
/// @notice Get denominator for deployer cut calculations
function getServiceProviderDeployerCutBase()
external view returns (uint256)
{
_requireIsInitialized();
return DEPLOYER_CUT_BASE;
}
/// @notice Get current deployer cut update lockup duration
function getDeployerCutLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return deployerCutLockupDuration;
}
/// @notice Get total number of service providers for a given serviceType
function getTotalServiceTypeProviders(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderTypeIDs[_serviceType];
}
/// @notice Get service provider id for an endpoint
function getServiceProviderIdFromEndpoint(string calldata _endpoint)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
}
/**
* @notice Get service provider ids for a given service provider and service type
* @return List of service ids of that type for a service provider
*/
function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType)
external view returns (uint256[] memory)
{
_requireIsInitialized();
return serviceProviderAddressToId[_ownerAddress][_serviceType];
}
/**
* @notice Get information about a service endpoint given its service id
* @param _serviceType - type of service, must be a valid service from ServiceTypeManager
* @param _serviceId - id of service
*/
function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId)
external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet)
{
_requireIsInitialized();
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId];
return (
serviceEndpoint.owner,
serviceEndpoint.endpoint,
serviceEndpoint.blocknumber,
serviceEndpoint.delegateOwnerWallet
);
}
/**
* @notice Get information about a service provider given their address
* @param _serviceProvider - address of service provider
*/
function getServiceProviderDetails(address _serviceProvider)
external view returns (
uint256 deployerStake,
uint256 deployerCut,
bool validBounds,
uint256 numberOfEndpoints,
uint256 minAccountStake,
uint256 maxAccountStake)
{
_requireIsInitialized();
return (
spDetails[_serviceProvider].deployerStake,
spDetails[_serviceProvider].deployerCut,
spDetails[_serviceProvider].validBounds,
spDetails[_serviceProvider].numberOfEndpoints,
spDetails[_serviceProvider].minAccountStake,
spDetails[_serviceProvider].maxAccountStake
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingDecreaseStakeRequest(address _serviceProvider)
external view returns (uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
decreaseStakeRequests[_serviceProvider].decreaseAmount,
decreaseStakeRequests[_serviceProvider].lockupExpiryBlock
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingUpdateDeployerCutRequest(address _serviceProvider)
external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
updateDeployerCutRequests[_serviceProvider].newDeployerCut,
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock
);
}
/// @notice Get current unstake lockup duration
function getDecreaseStakeLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return decreaseStakeLockupDuration;
}
/**
* @notice Validate that the total service provider balance is between the min and max stakes
for all their registered services and validate direct stake for sp is above minimum
* @param _serviceProvider - address of service provider
*/
function validateAccountStakeBalance(address _serviceProvider)
external view
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_validateBalanceInternal(
_serviceProvider,
Staking(stakingAddress).totalStakedFor(_serviceProvider)
);
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the ServiceTypeManager address
function getServiceTypeManagerAddress() external view returns (address) {
_requireIsInitialized();
return serviceTypeManagerAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _address - address for new Staking contract
*/
function setStakingAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _address;
emit StakingAddressUpdated(_address);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _address - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _address;
emit DelegateManagerAddressUpdated(_address);
}
/**
* @notice Set the ServiceTypeManager address
* @dev Only callable by Governance address
* @param _address - address for new ServiceTypeManager contract
*/
function setServiceTypeManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceTypeManagerAddress = _address;
emit ServiceTypeManagerAddressUpdated(_address);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _address - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _address;
emit ClaimsManagerAddressUpdated(_address);
}
// ========================================= Internal Functions =========================================
/**
* @notice Update status in spDetails if the bounds for a service provider is valid
*/
function _updateServiceProviderBoundStatus(address _serviceProvider) internal {
// Validate bounds for total stake
uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider);
if (totalSPStake < spDetails[_serviceProvider].minAccountStake ||
totalSPStake > spDetails[_serviceProvider].maxAccountStake) {
// Indicate this service provider is out of bounds
spDetails[_serviceProvider].validBounds = false;
} else {
// Indicate this service provider is within bounds
spDetails[_serviceProvider].validBounds = true;
}
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceProviderFactory: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the deployer cut lockup duration
* @param _duration - incoming duration
*/
function _updateDeployerCutLockupDuration(uint256 _duration) internal
{
require(
ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration,
"ServiceProviderFactory: Incoming duration must be greater than funding round block diff"
);
deployerCutLockupDuration = _duration;
}
/**
* @notice Set the decrease stake lockup duration
* @param _duration - incoming duration
*/
function _updateDecreaseStakeLockupDuration(uint256 _duration) internal
{
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
decreaseStakeLockupDuration = _duration;
}
/**
* @notice Compare a given amount input against valid min and max bounds for service provider
* @param _serviceProvider - address of service provider
* @param _amount - amount in wei to compare
*/
function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view
{
require(
_amount <= spDetails[_serviceProvider].maxAccountStake,
"ServiceProviderFactory: Maximum stake amount exceeded"
);
require(
spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake,
"ServiceProviderFactory: Minimum stake requirement not met"
);
}
/**
* @notice Get whether a decrease request has been initiated for service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether decrease request has been initiated
*/
function _decreaseRequestIsPending(address _serviceProvider)
internal view returns (bool)
{
return (
(decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) &&
(decreaseStakeRequests[_serviceProvider].decreaseAmount > 0)
);
}
/**
* @notice Boolean indicating whether a claim is pending for this service provider
*/
/**
* @notice Get whether a claim is pending for this service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether claim is pending
*/
function _claimPending(address _serviceProvider) internal view returns (bool) {
return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider);
}
// ========================================= Private Functions =========================================
function _requirePendingDeployerCutOperation (address _serviceProvider) private view {
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0),
"ServiceProviderFactory: No update deployer cut operation pending"
);
}
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"ServiceProviderFactory: stakingAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ServiceProviderFactory: delegateManagerAddress is not set"
);
}
function _requireServiceTypeManagerAddressIsSet() private view {
require(
serviceTypeManagerAddress != address(0x00),
"ServiceProviderFactory: serviceTypeManagerAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"ServiceProviderFactory: claimsManagerAddress is not set"
);
}
}
// File: contracts/DelegateManager.sol
pragma solidity ^0.5.0;
/// @notice SafeMath imported via ServiceProviderFactory.sol
/// @notice Governance imported via Staking.sol
/**
* Designed to manage delegation to staking contract
*/
contract DelegateManagerV2 is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"DelegateManager: Only callable by Governance contract"
);
string private constant ERROR_MINIMUM_DELEGATION = (
"DelegateManager: Minimum delegation amount required"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"DelegateManager: Only callable by target SP or governance"
);
string private constant ERROR_DELEGATOR_STAKE = (
"DelegateManager: Delegator must be staked for SP"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private claimsManagerAddress;
/**
* Period in blocks an undelegate operation is delayed.
* The undelegate operation speed bump is to prevent a delegator from
* attempting to remove their delegation in anticipation of a slash.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private undelegateLockupDuration;
/// @notice Maximum number of delegators a single account can handle
uint256 private maxDelegators;
/// @notice Minimum amount of delegation allowed
uint256 private minDelegationAmount;
/**
* Lockup duration for a remove delegator request.
* The remove delegator speed bump is to prevent a service provider from maliciously
* removing a delegator prior to the evaluation of a proposal.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private removeDelegatorLockupDuration;
/**
* Evaluation period for a remove delegator request
* @notice added to expiry block calculated for removeDelegatorLockupDuration
*/
uint256 private removeDelegatorEvalDuration;
// Staking contract ref
ERC20Mintable private audiusToken;
// Struct representing total delegated to SP and list of delegators
struct ServiceProviderDelegateInfo {
uint256 totalDelegatedStake;
uint256 totalLockedUpStake;
address[] delegators;
}
// Data structures for lockup during withdrawal
struct UndelegateStakeRequest {
address serviceProvider;
uint256 amount;
uint256 lockupExpiryBlock;
}
// Service provider address -> ServiceProviderDelegateInfo
mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo;
// Delegator stake by address delegated to
// delegator -> (service provider -> delegatedStake)
mapping (address => mapping(address => uint256)) private delegateInfo;
// Delegator stake total by address
// delegator -> (totalDelegated)
// Note - delegator properties are maintained in a mapping instead of struct
// in order to facilitate extensibility in the future.
mapping (address => uint256) private delegatorTotalStake;
// Requester to pending undelegate request
mapping (address => UndelegateStakeRequest) private undelegateRequests;
// Pending remove delegator requests
// service provider -> (delegator -> lockupExpiryBlock)
mapping (address => mapping (address => uint256)) private removeDelegatorRequests;
event IncreaseDelegatedStake(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _increaseAmount
);
event UndelegateStakeRequested(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount,
uint256 _lockupExpiryBlock
);
event UndelegateStakeRequestCancelled(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event UndelegateStakeRequestEvaluated(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event Claim(
address indexed _claimer,
uint256 indexed _rewards,
uint256 indexed _newTotal
);
event Slash(
address indexed _target,
uint256 indexed _amount,
uint256 indexed _newTotal
);
event RemoveDelegatorRequested(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _lockupExpiryBlock
);
event RemoveDelegatorRequestCancelled(
address indexed _serviceProvider,
address indexed _delegator
);
event RemoveDelegatorRequestEvaluated(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _unstakedAmount
);
event MaxDelegatorsUpdated(uint256 indexed _maxDelegators);
event MinDelegationUpdated(uint256 indexed _minDelegationAmount);
event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration);
event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration);
// ========================================= New State Variables =========================================
string private constant ERROR_ONLY_SERVICE_PROVIDER = (
"DelegateManager: Only callable by valid Service Provider"
);
// minDelegationAmount per service provider
mapping (address => uint256) private spMinDelegationAmounts;
event SPMinDelegationAmountUpdated(
address indexed _serviceProvider,
uint256 indexed _spMinDelegationAmount
);
// ========================================= Modifier Functions =========================================
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _tokenAddress,
address _governanceAddress,
uint256 _undelegateLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
maxDelegators = 175;
// Default minimum delegation amount set to 100AUD
minDelegationAmount = 100 * 10**uint256(18);
InitializableV2.initialize();
_updateUndelegateLockupDuration(_undelegateLockupDuration);
// 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks
_updateRemoveDelegatorLockupDuration(46523);
// 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks
removeDelegatorEvalDuration = 6646;
}
/**
* @notice Allow a delegator to delegate stake to a service provider
* @param _targetSP - address of service provider to delegate to
* @param _amount - amount in wei to delegate
* @return Updated total amount delegated to the service provider by delegator
*/
function delegateStake(
address _targetSP,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
!_claimPending(_targetSP),
"DelegateManager: Delegation not permitted for SP pending claim"
);
address delegator = msg.sender;
Staking stakingContract = Staking(stakingAddress);
// Stake on behalf of target service provider
stakingContract.delegateStakeFor(
_targetSP,
delegator,
_amount
);
// Update list of delegators to SP if necessary
if (!_delegatorExistsForSP(delegator, _targetSP)) {
// If not found, update list of delegates
spDelegateInfo[_targetSP].delegators.push(delegator);
require(
spDelegateInfo[_targetSP].delegators.length <= maxDelegators,
"DelegateManager: Maximum delegators exceeded"
);
}
// Update following values in storage through helper
// totalServiceProviderDelegatedStake = current sp total + new amount,
// totalStakedForSpFromDelegator = current delegator total for sp + new amount,
// totalDelegatorStake = current delegator total + new amount
_updateDelegatorStake(
delegator,
_targetSP,
spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount),
delegateInfo[delegator][_targetSP].add(_amount),
delegatorTotalStake[delegator].add(_amount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
require(
(delegateInfo[delegator][_targetSP] >= minDelegationAmount &&
delegateInfo[delegator][_targetSP] >= spMinDelegationAmounts[_targetSP]
),
ERROR_MINIMUM_DELEGATION
);
// Validate balance
ServiceProviderFactory(
serviceProviderFactoryAddress
).validateAccountStakeBalance(_targetSP);
emit IncreaseDelegatedStake(
delegator,
_targetSP,
_amount
);
// Return new total
return delegateInfo[delegator][_targetSP];
}
/**
* @notice Submit request for undelegation
* @param _target - address of service provider to undelegate stake from
* @param _amount - amount in wei to undelegate
* @return Updated total amount delegated to the service provider by delegator
*/
function requestUndelegateStake(
address _target,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
_amount > 0,
"DelegateManager: Requested undelegate stake amount must be greater than zero"
);
require(
!_claimPending(_target),
"DelegateManager: Undelegate request not permitted for SP pending claim"
);
address delegator = msg.sender;
require(
_delegatorExistsForSP(delegator, _target),
ERROR_DELEGATOR_STAKE
);
// Confirm no pending delegation request
require(
!_undelegateRequestIsPending(delegator),
"DelegateManager: No pending lockup expected"
);
// Ensure valid bounds
uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target];
require(
_amount <= currentlyDelegatedToSP,
"DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider"
);
// Submit updated request for sender, with target sp, undelegate amount, target expiry block
uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration);
_updateUndelegateStakeRequest(
delegator,
_target,
_amount,
lockupExpiryBlock
);
// Update total locked for this service provider, increasing by unstake amount
_updateServiceProviderLockupAmount(
_target,
spDelegateInfo[_target].totalLockedUpStake.add(_amount)
);
emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock);
return delegateInfo[delegator][_target].sub(_amount);
}
/**
* @notice Cancel undelegation request
*/
function cancelUndelegateStakeRequest() external {
_requireIsInitialized();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
uint256 unstakeAmount = undelegateRequests[delegator].amount;
address unlockFundsSP = undelegateRequests[delegator].serviceProvider;
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
unlockFundsSP,
spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount)
);
// Remove pending request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount);
}
/**
* @notice Finalize undelegation request and withdraw stake
* @return New total amount currently staked after stake has been undelegated
*/
function undelegateStake() external returns (uint256) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
// Confirm lockup expiry has expired
require(
undelegateRequests[delegator].lockupExpiryBlock <= block.number,
"DelegateManager: Lockup must be expired"
);
// Confirm no pending claim for this service provider
require(
!_claimPending(undelegateRequests[delegator].serviceProvider),
"DelegateManager: Undelegate not permitted for SP pending claim"
);
address serviceProvider = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
serviceProvider,
delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
delegator,
serviceProvider,
spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[delegator][serviceProvider].sub(unstakeAmount),
delegatorTotalStake[delegator].sub(unstakeAmount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
// Only exception is when delegating entire stake down to 0
require(
(
delegateInfo[delegator][serviceProvider] >= minDelegationAmount &&
delegateInfo[delegator][serviceProvider] >= spMinDelegationAmounts[serviceProvider]
) || delegateInfo[delegator][serviceProvider] == 0,
ERROR_MINIMUM_DELEGATION
);
// Remove from delegators list if no delegated stake remaining
if (delegateInfo[delegator][serviceProvider] == 0) {
_removeFromDelegatorsList(serviceProvider, delegator);
}
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
serviceProvider,
spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount)
);
// Reset undelegate request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestEvaluated(
delegator,
serviceProvider,
unstakeAmount
);
// Need to update service provider's `validBounds` flag
// Only way to do this is through `SPFactory.updateServiceProviderStake()`
// So we call it with the existing `spDeployerStake`
(uint256 spDeployerStake,,,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(serviceProvider)
);
ServiceProviderFactory(serviceProviderFactoryAddress).updateServiceProviderStake(
serviceProvider, spDeployerStake
);
// Return new total
return delegateInfo[delegator][serviceProvider];
}
/**
* @notice Claim and distribute rewards to delegators and service provider as necessary
* @param _serviceProvider - Provider for which rewards are being distributed
* @dev Factors in service provider rewards from delegator and transfers deployer cut
*/
function claimRewards(address _serviceProvider) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager))
(
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
) = _validateClaimRewards(spFactory, _serviceProvider);
// No-op if balance is already equivalent
// This case can occur if no rewards due to bound violation or all stake is locked
if (totalRewards == 0) {
return;
}
uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards(
_serviceProvider,
totalActiveFunds,
totalRewards,
deployerCut,
spFactory.getServiceProviderDeployerCutBase()
);
// Update total delegated to this SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = (
spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease)
);
// spRewardShare represents rewards directly allocated to service provider for their stake
// Value is computed as the remainder of total minted rewards after distribution to
// delegators, eliminating any potential for precision loss.
uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease);
// Adding the newly calculated reward share to current balance
uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare);
require(
totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake),
"DelegateManager: claimRewards amount mismatch"
);
spFactory.updateServiceProviderStake(
_serviceProvider,
newSPFactoryBalance
);
}
/**
* @notice Reduce current stake amount
* @dev Only callable by governance. Slashes service provider and delegators equally
* @param _amount - amount in wei to slash
* @param _slashAddress - address of service provider to slash
*/
function slash(uint256 _amount, address _slashAddress)
external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
Staking stakingContract = Staking(stakingAddress);
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Amount stored in staking contract for owner
uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress);
require(
(totalBalanceInStakingPreSlash >= _amount),
"DelegateManager: Cannot slash more than total currently staked"
);
// Cancel any withdrawal request for this service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress);
if (spLockedStake > 0) {
spFactory.cancelDecreaseStakeRequest(_slashAddress);
}
// Amount in sp factory for slash target
(uint256 totalBalanceInSPFactory,,,,,) = (
spFactory.getServiceProviderDetails(_slashAddress)
);
require(
totalBalanceInSPFactory > 0,
"DelegateManager: Service Provider stake required"
);
// Decrease value in Staking contract
// A value of zero slash will fail in staking, reverting this transaction
stakingContract.slash(_amount, _slashAddress);
uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress);
// Emit slash event
emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash);
uint256 totalDelegatedStakeDecrease = 0;
// For each delegator and deployer, recalculate new value
// newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash)
for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) {
address delegator = spDelegateInfo[_slashAddress].delegators[i];
uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress];
uint256 newDelegateStake = (
totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake)
).div(totalBalanceInStakingPreSlash);
// slashAmountForDelegator = preSlashDelegateStake - newDelegateStake;
delegateInfo[delegator][_slashAddress] = (
delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total stake for delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total decrease amount
totalDelegatedStakeDecrease = (
totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake))
);
// Check for any locked up funds for this slashed delegator
// Slash overrides any pending withdrawal requests
if (undelegateRequests[delegator].amount != 0) {
address unstakeSP = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Remove pending request
_updateServiceProviderLockupAmount(
unstakeSP,
spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount)
);
_resetUndelegateStakeRequest(delegator);
}
}
// Update total delegated to this SP
spDelegateInfo[_slashAddress].totalDelegatedStake = (
spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease)
);
// Remaining decrease applied to service provider
uint256 totalStakeDecrease = (
totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash)
);
uint256 totalSPFactoryBalanceDecrease = (
totalStakeDecrease.sub(totalDelegatedStakeDecrease)
);
spFactory.updateServiceProviderStake(
_slashAddress,
totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease)
);
}
/**
* @notice Initiate forcible removal of a delegator
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function requestRemoveDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] == 0,
"DelegateManager: Pending remove delegator request"
);
require(
_delegatorExistsForSP(_delegator, _serviceProvider),
ERROR_DELEGATOR_STAKE
);
// Update lockup
removeDelegatorRequests[_serviceProvider][_delegator] = (
block.number + removeDelegatorLockupDuration
);
emit RemoveDelegatorRequested(
_serviceProvider,
_delegator,
removeDelegatorRequests[_serviceProvider][_delegator]
);
}
/**
* @notice Cancel pending removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external {
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator);
}
/**
* @notice Evaluate removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
* @return Updated total amount delegated to the service provider by delegator
*/
function removeDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Enforce lockup expiry block
require(
block.number >= removeDelegatorRequests[_serviceProvider][_delegator],
"DelegateManager: Lockup must be expired"
);
// Enforce evaluation window for request
require(
block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration,
"DelegateManager: RemoveDelegator evaluation window expired"
);
uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider];
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
_serviceProvider,
_delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
_delegator,
_serviceProvider,
spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount),
delegatorTotalStake[_delegator].sub(unstakeAmount)
);
if (
_undelegateRequestIsPending(_delegator) &&
undelegateRequests[_delegator].serviceProvider == _serviceProvider
) {
// Remove pending request information
_updateServiceProviderLockupAmount(
_serviceProvider,
spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount)
);
_resetUndelegateStakeRequest(_delegator);
}
// Remove from list of delegators
_removeFromDelegatorsList(_serviceProvider, _delegator);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount);
}
/**
* @notice SP can update their minDelegationAmount
* @param _serviceProvider - address of service provider
* @param _spMinDelegationAmount - new minDelegationAmount for SP
* @notice does not enforce _spMinDelegationAmount >= minDelegationAmount since not necessary
* delegateStake() and undelegateStake() always take the max of both already
*/
function updateSPMinDelegationAmount(
address _serviceProvider,
uint256 _spMinDelegationAmount
) external {
_requireIsInitialized();
require(msg.sender == _serviceProvider, ERROR_ONLY_SERVICE_PROVIDER);
/**
* Ensure _serviceProvider is a valid SP
* No objective source of truth, closest heuristic is numEndpoints > 0
*/
(,,, uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress)
.getServiceProviderDetails(_serviceProvider)
);
require(numEndpoints > 0, ERROR_ONLY_SERVICE_PROVIDER);
spMinDelegationAmounts[_serviceProvider] = _spMinDelegationAmount;
emit SPMinDelegationAmountUpdated(_serviceProvider, _spMinDelegationAmount);
}
/**
* @notice Update duration for undelegate request lockup
* @param _duration - new lockup duration
*/
function updateUndelegateLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateUndelegateLockupDuration(_duration);
emit UndelegateLockupDurationUpdated(_duration);
}
/**
* @notice Update maximum delegators allowed
* @param _maxDelegators - new max delegators
*/
function updateMaxDelegators(uint256 _maxDelegators) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
maxDelegators = _maxDelegators;
emit MaxDelegatorsUpdated(_maxDelegators);
}
/**
* @notice Update minimum delegation amount
* @param _minDelegationAmount - min new min delegation amount
*/
function updateMinDelegationAmount(uint256 _minDelegationAmount) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
minDelegationAmount = _minDelegationAmount;
emit MinDelegationUpdated(_minDelegationAmount);
}
/**
* @notice Update remove delegator lockup duration
* @param _duration - new lockup duration
*/
function updateRemoveDelegatorLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateRemoveDelegatorLockupDuration(_duration);
emit RemoveDelegatorLockupDurationUpdated(_duration);
}
/**
* @notice Update remove delegator evaluation window duration
* @param _duration - new window duration
*/
function updateRemoveDelegatorEvalDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
removeDelegatorEvalDuration = _duration;
emit RemoveDelegatorEvalDurationUpdated(_duration);
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
governanceAddress = _governanceAddress;
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
emit ServiceProviderFactoryAddressUpdated(_spFactory);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _claimsManagerAddress - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _claimsManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManagerAddress;
emit ClaimsManagerAddressUpdated(_claimsManagerAddress);
}
// ========================================= View Functions =========================================
/**
* @notice Get list of delegators for a given service provider
* @param _sp - service provider address
*/
function getDelegatorsList(address _sp)
external view returns (address[] memory)
{
_requireIsInitialized();
return spDelegateInfo[_sp].delegators;
}
/**
* @notice Get total delegation from a given address
* @param _delegator - delegator address
*/
function getTotalDelegatorStake(address _delegator)
external view returns (uint256)
{
_requireIsInitialized();
return delegatorTotalStake[_delegator];
}
/// @notice Get total amount delegated to a service provider
function getTotalDelegatedToServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalDelegatedStake;
}
/// @notice Get total delegated stake locked up for a service provider
function getTotalLockedDelegationForServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalLockedUpStake;
}
/// @notice Get total currently staked for a delegator, for a given service provider
function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider)
external view returns (uint256)
{
_requireIsInitialized();
return delegateInfo[_delegator][_serviceProvider];
}
/**
* @notice Get status of pending undelegate request for a given address
* @param _delegator - address of the delegator
*/
function getPendingUndelegateRequest(address _delegator)
external view returns (address target, uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
UndelegateStakeRequest memory req = undelegateRequests[_delegator];
return (req.serviceProvider, req.amount, req.lockupExpiryBlock);
}
/**
* @notice Get status of pending remove delegator request for a given address
* @param _serviceProvider - address of the service provider
* @param _delegator - address of the delegator
* @return - current lockup expiry block for remove delegator request
*/
function getPendingRemoveDelegatorRequest(
address _serviceProvider,
address _delegator
) external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorRequests[_serviceProvider][_delegator];
}
/**
* @notice Get minDelegationAmount for given SP
* @param _serviceProvider - address of the service provider
* @return - minDelegationAmount for given SP
*/
function getSPMinDelegationAmount(address _serviceProvider) external view returns (uint256) {
return spMinDelegationAmounts[_serviceProvider];
}
/// @notice Get current undelegate lockup duration
function getUndelegateLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return undelegateLockupDuration;
}
/// @notice Current maximum delegators
function getMaxDelegators()
external view returns (uint256)
{
_requireIsInitialized();
return maxDelegators;
}
/// @notice Get minimum delegation amount
function getMinDelegationAmount()
external view returns (uint256)
{
_requireIsInitialized();
return minDelegationAmount;
}
/// @notice Get the duration for remove delegator request lockup
function getRemoveDelegatorLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorLockupDuration;
}
/// @notice Get the duration for evaluation of remove delegator operations
function getRemoveDelegatorEvalDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorEvalDuration;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
// ========================================= Internal functions =========================================
/**
* @notice Helper function for claimRewards to get balances from Staking contract
and do validation
* @param spFactory - reference to ServiceProviderFactory contract
* @param _serviceProvider - address for which rewards are being claimed
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut)
*/
function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider)
internal returns (
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
)
{
// Account for any pending locked up stake for the service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider);
uint256 totalLockedUpStake = (
spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake)
);
// Process claim for msg.sender
// Total locked parameter is equal to delegate locked up stake + service provider locked up stake
uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim(
_serviceProvider,
totalLockedUpStake
);
// Amount stored in staking contract for owner
totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider);
// Amount in sp factory for claimer
(
totalBalanceInSPFactory,
deployerCut,
,,,
) = spFactory.getServiceProviderDetails(_serviceProvider);
// Require active stake to claim any rewards
// Amount in delegate manager staked to service provider
uint256 totalBalanceOutsideStaking = (
totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake)
);
totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake);
require(
mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking),
"DelegateManager: Reward amount mismatch"
);
// Emit claim event
emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking);
return (
totalBalanceInStaking,
totalBalanceInSPFactory,
totalActiveFunds,
mintedRewards,
deployerCut
);
}
/**
* @notice Perform state updates when a delegate stake has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _totalServiceProviderDelegatedStake - total delegated to this service provider
* @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator
* @param _totalDelegatorStake - total delegated from this delegator address
*/
function _updateDelegatorStake(
address _delegator,
address _serviceProvider,
uint256 _totalServiceProviderDelegatedStake,
uint256 _totalStakedForSpFromDelegator,
uint256 _totalDelegatorStake
) internal
{
// Update total delegated for SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake;
// Update amount staked from this delegator to targeted service provider
delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator;
// Update total delegated from this delegator
_updateDelegatorTotalStake(_delegator, _totalDelegatorStake);
}
/**
* @notice Reset pending undelegate stake request
* @param _delegator - address of delegator
*/
function _resetUndelegateStakeRequest(address _delegator) internal
{
_updateUndelegateStakeRequest(_delegator, address(0), 0, 0);
}
/**
* @notice Perform updates when undelegate request state has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _amount - amount being undelegated
* @param _lockupExpiryBlock - block at which stake can be undelegated
*/
function _updateUndelegateStakeRequest(
address _delegator,
address _serviceProvider,
uint256 _amount,
uint256 _lockupExpiryBlock
) internal
{
// Update lockup information
undelegateRequests[_delegator] = UndelegateStakeRequest({
lockupExpiryBlock: _lockupExpiryBlock,
amount: _amount,
serviceProvider: _serviceProvider
});
}
/**
* @notice Update total amount delegated from an address
* @param _delegator - address of service provider
* @param _amount - updated delegator total
*/
function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal
{
delegatorTotalStake[_delegator] = _amount;
}
/**
* @notice Update amount currently locked up for this service provider
* @param _serviceProvider - address of service provider
* @param _updatedLockupAmount - updated lock up amount
*/
function _updateServiceProviderLockupAmount(
address _serviceProvider,
uint256 _updatedLockupAmount
) internal
{
spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount;
}
function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
// Overwrite and shrink delegators list
spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1];
spDelegateInfo[_serviceProvider].delegators.length--;
break;
}
}
}
/**
* @notice Helper function to distribute rewards to any delegators
* @param _sp - service provider account tracked in staking
* @param _totalActiveFunds - total funds minus any locked stake
* @param _totalRewards - total rewaards generated in this round
* @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase
* @param _deployerCutBase - denominator value for calculating service provider cut as a %
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking)
*/
function _distributeDelegateRewards(
address _sp,
uint256 _totalActiveFunds,
uint256 _totalRewards,
uint256 _deployerCut,
uint256 _deployerCutBase
)
internal returns (uint256 totalDelegatedStakeIncrease)
{
// Traverse all delegates and calculate their rewards
// As each delegate reward is calculated, increment SP cut reward accordingly
for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) {
address delegator = spDelegateInfo[_sp].delegators[i];
uint256 delegateStakeToSP = delegateInfo[delegator][_sp];
// Subtract any locked up stake
if (undelegateRequests[delegator].serviceProvider == _sp) {
delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount);
}
// Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards)
uint256 rewardsPriorToSPCut = (
delegateStakeToSP.mul(_totalRewards)
).div(_totalActiveFunds);
// Multiply by deployer cut fraction to calculate reward for SP
// Operation constructed to perform all multiplication prior to division
// uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase);
// = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds);
uint256 spDeployerCut = (
(delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut)
).div(
_totalActiveFunds.mul(_deployerCutBase)
);
// Increase total delegate reward in DelegateManager
// Subtract SP reward from rewards to calculate delegate reward
// delegateReward = rewardsPriorToSPCut - spDeployerCut;
delegateInfo[delegator][_sp] = (
delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
// Update total for this delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
totalDelegatedStakeIncrease = (
totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut))
);
}
return (totalDelegatedStakeIncrease);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"DelegateManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the remove delegator lockup duration after validating against governance
* @param _duration - Incoming remove delegator duration value
*/
function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
removeDelegatorLockupDuration = _duration;
}
/**
* @notice Set the undelegate lockup duration after validating against governance
* @param _duration - Incoming undelegate lockup duration value
*/
function _updateUndelegateLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
undelegateLockupDuration = _duration;
}
/**
* @notice Returns if delegator has delegated to a service provider
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @return boolean indicating whether delegator exists for service provider
*/
function _delegatorExistsForSP(
address _delegator,
address _serviceProvider
) internal view returns (bool)
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
return true;
}
}
// Not found
return false;
}
/**
* @notice Determine if a claim is pending for this service provider
* @param _sp - address of service provider
* @return boolean indicating whether a claim is pending
*/
function _claimPending(address _sp) internal view returns (bool) {
ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress);
return claimsManager.claimPending(_sp);
}
/**
* @notice Determine if a decrease request has been initiated
* @param _delegator - address of delegator
* @return boolean indicating whether a decrease request is pending
*/
function _undelegateRequestIsPending(address _delegator) internal view returns (bool)
{
return (
(undelegateRequests[_delegator].lockupExpiryBlock != 0) &&
(undelegateRequests[_delegator].amount != 0) &&
(undelegateRequests[_delegator].serviceProvider != address(0))
);
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"DelegateManager: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"DelegateManager: serviceProviderFactoryAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"DelegateManager: claimsManagerAddress is not set"
);
}
}
|
Slashes `_amount` tokens from _slashAddress Callable from DelegateManager _amount - Number of tokens slashed _slashAddress - Address being slashed/ Burn slashed tokens from account
|
function slash(
uint256 _amount,
address _slashAddress
) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_burnFor(_slashAddress, _amount);
emit Slashed(
_slashAddress,
_amount,
totalStakedFor(_slashAddress)
);
}
| 1,231,729
|
./partial_match/84531/0xA39039AF66e9c7bd3CE53aa56B95F46D0b6BB364/sources/contracts/src/diamond/utils/cryptography/EIP712.sol
|
The hash of the version parameter for the EIP712 domain. NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead./ If the version is empty, the contract may have been upgraded without initializing the new storage. We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
|
function _EIP712VersionHash() internal view returns (bytes32) {
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
bytes32 hashedVersion = EIP712Storage.layout()._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
return keccak256("");
}
}
}
| 16,688,102
|
./partial_match/1/0x640f7B78830db57BAfDF6F462d2B458dA80825D3/sources/contracts/protocol/leverage/GeneralLevSwap.sol
|
This function is called after your contract has received the flash loaned amount overriding executeOperation() in IFlashLoanReceiver/ approve the Aave LendingPool contract allowance to pull the owed amount
|
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(initiator == address(this), Errors.LS_INVALID_CONFIGURATION);
require(msg.sender == AAVE_LENDING_POOL_ADDRESS, Errors.LS_INVALID_CONFIGURATION);
require(assets.length == amounts.length, Errors.LS_INVALID_CONFIGURATION);
require(assets.length == premiums.length, Errors.LS_INVALID_CONFIGURATION);
require(amounts[0] != 0, Errors.LS_INVALID_CONFIGURATION);
require(assets[0] != address(0), Errors.LS_INVALID_CONFIGURATION);
_executeOperation(assets[0], amounts[0], premiums[0], params);
IERC20(assets[0]).safeApprove(AAVE_LENDING_POOL_ADDRESS, 0);
IERC20(assets[0]).safeApprove(AAVE_LENDING_POOL_ADDRESS, amounts[0] + premiums[0]);
return true;
}
| 15,492,419
|
./full_match/1/0x48deE19C0e44c147934702c12dc98963CA831009/sources/src/Asset/ERC1155ERC721.sol
|
A distinct Uniform Resource Identifier (URI) for a given asset. id token to get the uri of. return URI string
|
function tokenURI(uint256 id) public view returns (string memory) {
require(_ownerOf(id) != address(0), "NFT does not exist");
return toFullURI(_metadataHash[id & URI_ID], id);
}
| 4,919,232
|
pragma solidity >=0.4.22 <0.6.0;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
address delegate;
}
struct Proposal {
uint voteCount;
}
struct Bribe {
uint amount;
uint8 vote;
}
address chairperson;
mapping(address => Voter) voters;
mapping(address => Bribe) public theBribe;
mapping (address => uint) pendingWithdraw;
Proposal[] proposals;
/// Create a new ballot with $(_numProposals) different proposals.
constructor(uint8 _numProposals) public {
require(_numProposals <= 254, "255 is reserved for TIE result");
chairperson = msg.sender;
voters[chairperson].weight = 1;
proposals.length = _numProposals;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function giveRightToVote(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
emit rightGiven(toVoter, voters[toVoter].weight);
}
// testing function
function haveRightToVote(address voter) public view returns (bool){
if(voters[voter].weight >= 1) return true;
}
/// Delegate your vote to the voter $(to).
/* solium-disable-next-line */
function delegate(address to) public {
Voter storage sender = voters[msg.sender];
if (sender.voted) return;
while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)
to = voters[to].delegate;
if (to == msg.sender) return;
sender.voted = true;
sender.delegate = to;
Voter storage delegateTo = voters[to];
if (delegateTo.voted)
proposals[delegateTo.vote].voteCount += sender.weight;
else
delegateTo.weight += sender.weight;
}
/// Give a single vote to proposal $(toProposal).
function vote(uint8 toProposal) public {
require(voters[msg.sender].voted == false, "Already votted");
require(voters[msg.sender].weight >= 1, "No rights to vote");
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
emit addressVoted(msg.sender, toProposal, false);
if(sender.vote == theBribe[msg.sender].vote){
uint amount = pendingWithdraw[msg.sender];
pendingWithdraw[msg.sender] = 0;
msg.sender.transfer(amount);
emit addressVoted(msg.sender, toProposal, true);
}
}
// testitng funtion
function votedFor(address voter) public view returns(uint8 proposal){
require(voters[voter].voted == true, "Address didn't vote");
return voters[voter].vote;
}
function winningProposal() public view returns (uint8 _winningProposal) {
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
} else if (proposals[prop].voteCount == winningVoteCount){
_winningProposal = 255;// IT's a tie !
}
}
function bribe(address _reciver, uint8 _vote) public payable {
require(_vote <= proposals.length, "Not valid vote option");
require(!voters[_reciver].voted, "Reciver already voted");
require(voters[_reciver].weight >= 1, "Reciver have no power to vote");
if(theBribe[_reciver].vote == _vote){
theBribe[_reciver].amount += msg.value;
pendingWithdraw[_reciver] += msg.value;
emit brodcastBribe(_reciver, _vote, msg.value, pendingWithdraw[_reciver]);
} else {
theBribe[_reciver].amount = msg.value;
theBribe[_reciver].vote = _vote;
pendingWithdraw[_reciver] = msg.value;
emit brodcastBribe(_reciver, _vote, msg.value, pendingWithdraw[_reciver]);
}
}
function getBribeInfo(address _reciver) public view returns (uint _amount, uint8 _vote ){
return (theBribe[_reciver].amount, theBribe[_reciver].vote);
}
event brodcastBribe(address _reciver, uint8 _vote, uint _amount, uint pendingWithdraw);
event rightGiven(address _reciver, uint _weight);
event addressVoted(address _voter, uint8 proposal, bool wasBribed);
}
|
Give $(toVoter) the right to vote on this ballot. May only be called by $(chairperson).
|
function giveRightToVote(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
emit rightGiven(toVoter, voters[toVoter].weight);
}
| 5,536,741
|
./full_match/4/0x011F0DA68ce3F80b2C8DCd6D94B2f36280ff3b6f/sources/contracts/ico.sol
|
_Stake is used to make a stake for an sender. It will remove the amount staked from the stakers account and place those tokens inside a stake container StakeID/ Simple check so that user does not stake 0 Mappings in solidity creates all values, but empty, so we can just check the address block.timestamp = timestamp of the current block in seconds since the epoch See if the staker already has a staked index or if its the first time This stakeholder stakes for the first time We need to add him to the stakeHolders and also map it into the Index of the stakes The index returned will be the index of the stakeholder in the stakeholders array
|
function _stake(uint256 _amount) internal{
require(_amount > 0, "Cannot stake nothing");
uint256 index = stakes[msg.sender];
uint256 timestamp = block.timestamp;
if((index == 0 && stakeholders[0].stake.amount == 0)||(index == 0 && stakeholders[0].user != msg.sender) ){
index = _addStakeholder(msg.sender);
stakeholders[index].stake=(Stake(msg.sender, _amount, timestamp,0));
}
else {
stakeholders[index].stake.amount+= _amount;
}
}
| 740,436
|
./partial_match/1/0xBf6E1F1Fd72080C4793e89aCB8FB61ef1A61cA67/sources/Proposal32.sol
|
Contracts and ERC20 addresses Withdraw USDC Comp transfers E compSend(0x8A8acf1cEcC4ed6Fe9c408449164CE2034AdC03f, 0, 0, 1); Chilly compSend(0x01e0C7b70E0E05a06c7cC8deeb97Fa03d6a77c9C, 0, 0, 1); Designer compSend(0x3FdcED6B5C1f176b543E5E0b841cB7224596C33C, 0, 0, 1); Ross Feddas compSend(0xbdac5657eDd13F47C3DD924eAa36Cf1Ec49672cc, 0, 0, 1); Mona compSend(0xdADc6F71986643d9e9CB368f08Eb6F1333F6d8f9, 0, 0, 1); Transfer remaining USDC to reserves
|
function execute() public {
withdrawToken(
address(USDC),
address(this),
IERC20(USDC).balanceOf(RESERVES)
);
compSend(0x88c868B1024ECAefDc648eb152e91C57DeA984d0, 6438, 0, 1);
uint256 usdcBalance = USDC.balanceOf(address(this));
USDC.transfer(RESERVES, usdcBalance);
executeStep++;
}
| 4,473,888
|
./partial_match/42/0x3e6d34F22878A10b8F49f4ba8B9d42cBc2fF0037/sources/EtherCollateralsUSD.sol
|
repay any accrued interests first Max repay is the accruedInterest amount
|
function _splitInterestLoanPayment(
uint256 _paymentAmount,
uint256 _accruedInterest,
uint256 _loanAmount
)
internal
pure
returns (
uint256 interestPaid,
uint256 loanAmountPaid,
uint256 accruedInterestAfter,
uint256 loanAmountAfter
)
{
uint256 remainingPayment = _paymentAmount;
accruedInterestAfter = _accruedInterest;
if (remainingPayment > 0 && _accruedInterest > 0) {
interestPaid = remainingPayment > _accruedInterest ? _accruedInterest : remainingPayment;
accruedInterestAfter = accruedInterestAfter.sub(interestPaid);
remainingPayment = remainingPayment.sub(interestPaid);
}
if (remainingPayment > 0) {
loanAmountAfter = loanAmountAfter.sub(remainingPayment);
loanAmountPaid = remainingPayment;
}
}
| 3,308,180
|
/**
*Submitted for verification at Etherscan.io on 2019-10-31
*/
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 Cyril Lapinte
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************
*
* Flatten Contract: Tokensale
*
* Git Commit:
* https://github.com/c-layer/contracts/tree/43925ba24cc22f42d0ff7711d0e169e8c2a0e09f
*
**************************************************************************/
// File: contracts/interface/IERC20.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract IERC20 {
function name() public view returns (string memory);
function symbol() public view returns (string memory);
function decimals() public view returns (uint256);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function increaseApproval(address spender, uint addedValue)
public returns (bool);
function decreaseApproval(address spender, uint subtractedValue)
public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/interface/ITokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title ITokensale
* @dev ITokensale interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
contract ITokensale {
function () external payable;
function investETH() public payable;
function token() public view returns (IERC20);
function vaultETH() public view returns (address);
function vaultERC20() public view returns (address);
function tokenPrice() public view returns (uint256);
function totalRaised() public view returns (uint256);
function totalUnspentETH() public view returns (uint256);
function totalRefundedETH() public view returns (uint256);
function availableSupply() public view returns (uint256);
function investorUnspentETH(address _investor) public view returns (uint256);
function investorInvested(address _investor) public view returns (uint256);
function investorTokens(address _investor) public view returns (uint256);
function tokenInvestment(address _investor, uint256 _amount) public view returns (uint256);
function refundManyUnspentETH(address payable[] memory _receivers) public returns (bool);
function refundUnspentETH() public returns (bool);
function withdrawAllETHFunds() public returns (bool);
function fundETH() public payable;
event RefundETH(address indexed recipient, uint256 amount);
event WithdrawETH(uint256 amount);
event FundETH(uint256 amount);
event Investment(address indexed investor, uint256 invested, uint256 tokens);
}
// File: contracts/util/math/SafeMath.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/util/governance/Ownable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/util/governance/Operable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Operable
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* OP01: Message sender must be an operator
* OP02: Address must be an operator
* OP03: Address must not be an operator
*/
contract Operable is Ownable {
mapping (address => bool) private operators_;
/**
* @dev Throws if called by any account other than the operator
*/
modifier onlyOperator {
require(operators_[msg.sender], "OP01");
_;
}
/**
* @dev constructor
*/
constructor() public {
defineOperator("Owner", msg.sender);
}
/**
* @dev isOperator
* @param _address operator address
*/
function isOperator(address _address) public view returns (bool) {
return operators_[_address];
}
/**
* @dev removeOperator
* @param _address operator address
*/
function removeOperator(address _address) public onlyOwner {
require(operators_[_address], "OP02");
operators_[_address] = false;
emit OperatorRemoved(_address);
}
/**
* @dev defineOperator
* @param _role operator role
* @param _address operator address
*/
function defineOperator(string memory _role, address _address)
public onlyOwner
{
require(!operators_[_address], "OP03");
operators_[_address] = true;
emit OperatorDefined(_role, _address);
}
event OperatorRemoved(address address_);
event OperatorDefined(
string role,
address address_
);
}
// File: contracts/util/lifecycle/Pausable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*
* Error messages
* PA01: the contract is paused
* PA02: the contract is unpaused
**/
contract Pausable is Operable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "PA01");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "PA02");
_;
}
/**
* @dev called by the operator to pause, triggers stopped state
*/
function pause() public onlyOperator whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the operator to unpause, returns to normal state
*/
function unpause() public onlyOperator whenPaused {
paused = false;
emit Unpause();
}
}
// File: contracts/tokensale/BaseTokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title BaseTokensale
* @dev Base Tokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* TOS01: token price must be strictly positive
* TOS02: price unit must be strictly positive
* TOS03: No data must be sent while sending ETH
* TOS04: Token transfer must be successfull
* TOS05: No ETH to refund
* TOS06: Cannot invest 0 tokens
* TOS07: Cannot invest if there are no tokens to buy
* TOS08: Only exact amount is authorized
*/
contract BaseTokensale is ITokensale, Operable, Pausable {
using SafeMath for uint256;
/* General sale details */
IERC20 internal token_;
address payable internal vaultETH_;
address internal vaultERC20_;
uint256 internal tokenPrice_;
uint256 internal priceUnit_;
uint256 internal totalRaised_;
uint256 internal totalTokensSold_;
uint256 internal totalUnspentETH_;
uint256 internal totalRefundedETH_;
struct Investor {
uint256 unspentETH;
uint256 invested;
uint256 tokens;
}
mapping(address => Investor) internal investors;
/**
* @dev constructor
*/
constructor(
IERC20 _token,
address _vaultERC20,
address payable _vaultETH,
uint256 _tokenPrice,
uint256 _priceUnit
) public
{
require(_tokenPrice > 0, "TOS01");
require(_priceUnit > 0, "TOS02");
token_ = _token;
vaultERC20_ = _vaultERC20;
vaultETH_ = _vaultETH;
tokenPrice_ = _tokenPrice;
priceUnit_ = _priceUnit;
}
/**
* @dev fallback function
*/
//solhint-disable-next-line no-complex-fallback
function () external payable {
require(msg.data.length == 0, "TOS03");
investETH();
}
/* Investment */
function investETH() public payable
{
Investor storage investor = investorInternal(msg.sender);
uint256 amountETH = investor.unspentETH.add(msg.value);
investInternal(msg.sender, amountETH, false);
}
/**
* @dev returns the token sold
*/
function token() public view returns (IERC20) {
return token_;
}
/**
* @dev returns the vault use to
*/
function vaultETH() public view returns (address) {
return vaultETH_;
}
/**
* @dev returns the vault to receive ETH
*/
function vaultERC20() public view returns (address) {
return vaultERC20_;
}
/**
* @dev returns token price
*/
function tokenPrice() public view returns (uint256) {
return tokenPrice_;
}
/**
* @dev returns price unit
*/
function priceUnit() public view returns (uint256) {
return priceUnit_;
}
/**
* @dev returns total raised
*/
function totalRaised() public view returns (uint256) {
return totalRaised_;
}
/**
* @dev returns total tokens sold
*/
function totalTokensSold() public view returns (uint256) {
return totalTokensSold_;
}
/**
* @dev returns total unspent ETH
*/
function totalUnspentETH() public view returns (uint256) {
return totalUnspentETH_;
}
/**
* @dev returns total refunded ETH
*/
function totalRefundedETH() public view returns (uint256) {
return totalRefundedETH_;
}
/**
* @dev returns the available supply
*/
function availableSupply() public view returns (uint256) {
uint256 vaultSupply = token_.balanceOf(vaultERC20_);
uint256 allowance = token_.allowance(vaultERC20_, address(this));
return (vaultSupply < allowance) ? vaultSupply : allowance;
}
/* Investor specific attributes */
function investorUnspentETH(address _investor)
public view returns (uint256)
{
return investorInternal(_investor).unspentETH;
}
function investorInvested(address _investor)
public view returns (uint256)
{
return investorInternal(_investor).invested;
}
function investorTokens(address _investor) public view returns (uint256) {
return investorInternal(_investor).tokens;
}
/**
* @dev tokenInvestment
*/
function tokenInvestment(address, uint256 _amount)
public view returns (uint256)
{
uint256 availableSupplyValue = availableSupply();
uint256 contribution = _amount.mul(priceUnit_).div(tokenPrice_);
return (contribution < availableSupplyValue) ? contribution : availableSupplyValue;
}
/**
* @dev refund unspentETH ETH many
*/
function refundManyUnspentETH(address payable[] memory _receivers)
public onlyOperator returns (bool)
{
for (uint256 i = 0; i < _receivers.length; i++) {
refundUnspentETHInternal(_receivers[i]);
}
return true;
}
/**
* @dev refund unspentETH
*/
function refundUnspentETH() public returns (bool) {
refundUnspentETHInternal(msg.sender);
return true;
}
/**
* @dev withdraw all ETH funds
*/
function withdrawAllETHFunds() public onlyOperator returns (bool) {
uint256 balance = address(this).balance;
withdrawETHInternal(balance);
return true;
}
/**
* @dev fund ETH
*/
function fundETH() public payable onlyOperator {
emit FundETH(msg.value);
}
/**
* @dev investor internal
*/
function investorInternal(address _investor)
internal view returns (Investor storage)
{
return investors[_investor];
}
/**
* @dev eval unspent ETH internal
*/
function evalUnspentETHInternal(
Investor storage _investor, uint256 _investedETH
) internal view returns (uint256)
{
return _investor.unspentETH.add(msg.value).sub(_investedETH);
}
/**
* @dev eval investment internal
*/
function evalInvestmentInternal(uint256 _tokens)
internal view returns (uint256, uint256)
{
uint256 invested = _tokens.mul(tokenPrice_).div(priceUnit_);
return (invested, _tokens);
}
/**
* @dev distribute tokens internal
*/
function distributeTokensInternal(address _investor, uint256 _tokens) internal {
require(
token_.transferFrom(vaultERC20_, _investor, _tokens),
"TOS04");
}
/**
* @dev refund unspentETH internal
*/
function refundUnspentETHInternal(address payable _investor) internal {
Investor storage investor = investorInternal(_investor);
require(investor.unspentETH > 0, "TOS05");
uint256 unspentETH = investor.unspentETH;
totalRefundedETH_ = totalRefundedETH_.add(unspentETH);
totalUnspentETH_ = totalUnspentETH_.sub(unspentETH);
investor.unspentETH = 0;
// Multiple sends are required for refundManyUnspentETH
// solhint-disable-next-line multiple-sends
_investor.transfer(unspentETH);
emit RefundETH(_investor, unspentETH);
}
/**
* @dev withdraw ETH internal
*/
function withdrawETHInternal(uint256 _amount) internal {
// Send is used after the ERC20 transfer
// solhint-disable-next-line multiple-sends
vaultETH_.transfer(_amount);
emit WithdrawETH(_amount);
}
/**
* @dev invest internal
*/
function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly)
internal whenNotPaused
{
require(_amount != 0, "TOS06");
Investor storage investor = investorInternal(_investor);
uint256 investment = tokenInvestment(_investor, _amount);
require(investment != 0, "TOS07");
(uint256 invested, uint256 tokens) = evalInvestmentInternal(investment);
if (_exactAmountOnly) {
require(invested == _amount, "TOS08");
} else {
uint256 unspentETH = evalUnspentETHInternal(investor, invested);
totalUnspentETH_ = totalUnspentETH_.sub(investor.unspentETH).add(unspentETH);
investor.unspentETH = unspentETH;
}
investor.invested = investor.invested.add(invested);
investor.tokens = investor.tokens.add(tokens);
totalRaised_ = totalRaised_.add(invested);
totalTokensSold_ = totalTokensSold_.add(tokens);
emit Investment(_investor, invested, tokens);
/* Reentrancy risks: No state change must come below */
distributeTokensInternal(_investor, tokens);
uint256 balance = address(this).balance;
uint256 withdrawableETH = balance.sub(totalUnspentETH_);
if (withdrawableETH != 0) {
withdrawETHInternal(withdrawableETH);
}
}
}
// File: contracts/tokensale/SchedulableTokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title SchedulableTokensale
* @dev SchedulableTokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* STS01: It must be before the sale is opened
* STS02: Sale must be open
* STS03: It must be before the sale is closed
* STS04: It must be after the sale is closed
* STS05: It must start before it ends.
*/
contract SchedulableTokensale is BaseTokensale {
uint256 internal startAt = ~uint256(0);
uint256 internal endAt = ~uint256(0);
bool internal closed;
event Schedule(uint256 startAt, uint256 endAt);
event CloseEarly();
/**
* @dev Throws if sale is not open
*/
modifier beforeSaleIsOpened {
require(currentTime() < startAt && !closed, "STS01");
_;
}
/**
* @dev Throws if sale is not open
*/
modifier saleIsOpened {
require(
currentTime() >= startAt
&& currentTime() <= endAt
&& !closed, "STS02"
);
_;
}
/**
* @dev Throws once the sale is closed
*/
modifier beforeSaleIsClosed {
require(currentTime() <= endAt && !closed, "STS03");
_;
}
/**
* @dev Throws once the sale is closed
*/
modifier afterSaleIsClosed {
require(isClosed(), "STS04");
_;
}
/**
* @dev constructor
*/
constructor(
IERC20 _token,
address _vaultERC20,
address payable _vaultETH,
uint256 _tokenPrice,
uint256 _priceUnit
) public
BaseTokensale(_token, _vaultERC20, _vaultETH, _tokenPrice, _priceUnit)
{} /* solhint-disable no-empty-blocks */
/**
* @dev schedule
*/
function schedule() public view returns (uint256, uint256) {
return (startAt, endAt);
}
/**
* @dev isClosed
*/
function isClosed() public view returns (bool) {
return currentTime() > endAt || closed;
}
/**
* @dev update schedule
*/
function updateSchedule(uint256 _startAt, uint256 _endAt)
public onlyOperator beforeSaleIsOpened
{
require(_startAt < _endAt, "STS05");
startAt = _startAt;
endAt = _endAt;
emit Schedule(_startAt, _endAt);
}
/**
* @dev close sale
*/
function closeEarly()
public onlyOperator beforeSaleIsClosed
{
closed = true;
emit CloseEarly();
}
/* Investment */
function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly) internal
saleIsOpened
{
super.investInternal(_investor, _amount, _exactAmountOnly);
}
/* Util */
/**
* @dev current time
*/
function currentTime() internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return now;
}
}
// File: contracts/tokensale/BonusTokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title BonusTokensale
* @dev BonusTokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* BT01: There must have the same number of bonuses and bonusUntils
* BT02: There must be some bonuses
* BT03: There cannot be too many bonuses
* BT04: BonusUntils must be declared in a progressive order
* BT05: There cannot be bonuses with a NONE bonus mode
**/
contract BonusTokensale is SchedulableTokensale {
enum BonusMode { NONE, EARLY, FIRST }
uint256 constant MAX_BONUSES = 10;
BonusMode internal bonusMode_ = BonusMode.NONE;
uint256[] internal bonusUntils_;
uint256[] internal bonuses_;
event BonusesDefined(uint256[] bonuses, BonusMode bonusMode, uint256[] bonusUntils);
/**
* @dev constructor
*/
constructor(
IERC20 _token,
address _vaultERC20,
address payable _vaultETH,
uint256 _tokenPrice,
uint256 _priceUnit
) public
SchedulableTokensale(_token,
_vaultERC20, _vaultETH, _tokenPrice, _priceUnit)
{} /* solhint-disable no-empty-blocks */
/**
* @dev bonuses
*/
function bonuses() public view returns (BonusMode, uint256[] memory, uint256[] memory) {
return (bonusMode_, bonuses_, bonusUntils_);
}
/**
* @dev early bonus
*/
function earlyBonus(uint256 _currentTime)
public view returns (uint256 bonus, uint256 remainingAtBonus)
{
if (bonusMode_ != BonusMode.EARLY
|| _currentTime < startAt || _currentTime > endAt) {
return (uint256(0), uint256(-1));
}
for(uint256 i=0; i < bonusUntils_.length; i++) {
if (_currentTime <= bonusUntils_[i]) {
return (bonuses_[i], uint256(-1));
}
}
return (uint256(0), uint256(-1));
}
/**
* @dev first bonus
*/
function firstBonus(uint256 _tokensSold)
public view returns (uint256 bonus, uint256 remainingAtBonus)
{
if (bonusMode_ != BonusMode.FIRST) {
return (uint256(0), uint256(-1));
}
for(uint256 i=0; i < bonusUntils_.length; i++) {
if (_tokensSold < bonusUntils_[i]) {
return (bonuses_[i], bonusUntils_[i]-_tokensSold);
}
}
return (uint256(0), uint256(-1));
}
/**
* @dev define bonus
*/
function defineBonuses(
BonusMode _bonusMode,
uint256[] memory _bonuses,
uint256[] memory _bonusUntils)
public onlyOperator beforeSaleIsOpened returns (bool)
{
require(_bonuses.length == _bonusUntils.length, "BT01");
if (_bonusMode != BonusMode.NONE) {
require(_bonusUntils.length > 0, "BT02");
require(_bonusUntils.length < MAX_BONUSES, "BT03");
uint256 bonusUntil =
(_bonusMode == BonusMode.EARLY) ? startAt : 0;
for(uint256 i=0; i < _bonusUntils.length; i++) {
require(_bonusUntils[i] > bonusUntil, "BT04");
bonusUntil = _bonusUntils[i];
}
} else {
require(_bonusUntils.length == 0, "BT05");
}
bonuses_ = _bonuses;
bonusMode_ = _bonusMode;
bonusUntils_ = _bonusUntils;
emit BonusesDefined(_bonuses, _bonusMode, _bonusUntils);
return true;
}
/**
* @dev current bonus
*/
function tokenBonus(uint256 _tokens)
public view returns (uint256 tokenBonus_)
{
uint256 bonus;
uint256 remainingAtBonus;
uint256 unprocessed = _tokens;
do {
if(bonusMode_ == BonusMode.EARLY) {
(bonus, remainingAtBonus) = earlyBonus(currentTime());
}
if(bonusMode_ == BonusMode.FIRST) {
(bonus, remainingAtBonus) =
firstBonus(totalTokensSold_+_tokens-unprocessed);
}
uint256 tokensAtCurrentBonus =
(unprocessed < remainingAtBonus) ? unprocessed : remainingAtBonus;
tokenBonus_ += bonus.mul(tokensAtCurrentBonus).div(100);
unprocessed -= tokensAtCurrentBonus;
} while(bonus > 0 && unprocessed > 0 && remainingAtBonus > 0);
}
/**
* @dev eval investment internal
*/
function evalInvestmentInternal(uint256 _tokens)
internal view returns (uint256, uint256)
{
(uint256 invested, uint256 tokens) = super.evalInvestmentInternal(_tokens);
uint256 bonus = tokenBonus(tokens);
return (invested, tokens.add(bonus));
}
}
// File: contracts/interface/IRatesProvider.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IRatesProvider
* @dev IRatesProvider interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
contract IRatesProvider {
function defineRatesExternal(uint256[] calldata _rates) external returns (bool);
function name() public view returns (string memory);
function rate(bytes32 _currency) public view returns (uint256);
function currencies() public view
returns (bytes32[] memory, uint256[] memory, uint256);
function rates() public view returns (uint256, uint256[] memory);
function convert(uint256 _amount, bytes32 _fromCurrency, bytes32 _toCurrency)
public view returns (uint256);
function defineCurrencies(
bytes32[] memory _currencies,
uint256[] memory _decimals,
uint256 _rateOffset) public returns (bool);
function defineRates(uint256[] memory _rates) public returns (bool);
event RateOffset(uint256 rateOffset);
event Currencies(bytes32[] currencies, uint256[] decimals);
event Rate(bytes32 indexed currency, uint256 rate);
}
// File: contracts/tokensale/ChangeTokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title ChangeTokensale
* @dev ChangeTokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* CTS01: message value must be positive
* CTS02: No investment after currency change.
*/
contract ChangeTokensale is BaseTokensale {
bytes32 internal baseCurrency_;
IRatesProvider internal ratesProvider_;
uint256 internal totalReceivedETH_;
/* Investment */
function investETH() public payable
{
require(msg.value > 0, "CTS01");
totalReceivedETH_ = totalReceivedETH_.add(msg.value);
Investor storage investor = investorInternal(msg.sender);
uint256 amountETH = investor.unspentETH.add(msg.value);
uint256 amountCurrency =
ratesProvider_.convert(amountETH, "ETH", baseCurrency_);
require(amountCurrency > 0, "CTS02");
investInternal(msg.sender, amountCurrency, false);
}
/**
* @dev returns baseCurrency
*/
function baseCurrency() public view returns (bytes32) {
return baseCurrency_;
}
/**
* @dev returns ratesProvider
*/
function ratesProvider() public view returns (IRatesProvider) {
return ratesProvider_;
}
/**
* @dev returns totalRaisedETH
*/
function totalRaisedETH() public view returns (uint256) {
return totalReceivedETH_.sub(totalUnspentETH_).sub(totalRefundedETH_);
}
/**
* @dev returns totalReceivedETH
*/
function totalReceivedETH() public view returns (uint256) {
return totalReceivedETH_;
}
/**
* @dev add offchain investment
*/
function addOffchainInvestment(address _investor, uint256 _amount)
public onlyOperator returns (bool)
{
investInternal(_investor, _amount, true);
return true;
}
/**
* @dev eval unspent ETH
*/
function evalUnspentETHInternal(
Investor storage _investor, uint256 _invested
) internal view returns (uint256)
{
uint256 investedETH =
ratesProvider_.convert(_invested, baseCurrency_, "ETH");
return super.evalUnspentETHInternal(_investor, investedETH);
}
}
// File: contracts/interface/IUserRegistry.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IUserRegistry
* @dev IUserRegistry interface
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
**/
contract IUserRegistry {
event UserRegistered(uint256 indexed userId, address address_, uint256 validUntilTime);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
event UserSuspended(uint256 indexed userId);
event UserRestored(uint256 indexed userId);
event UserValidity(uint256 indexed userId, uint256 validUntilTime);
event UserExtendedKey(uint256 indexed userId, uint256 key, uint256 value);
event UserExtendedKeys(uint256 indexed userId, uint256[] values);
event ExtendedKeysDefinition(uint256[] keys);
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
external returns (bool);
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external returns (bool);
function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses)
external returns (bool);
function detachManyAddressesExternal(address[] calldata _addresses)
external returns (bool);
function suspendManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function restoreManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external returns (bool);
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external returns (bool);
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) external returns (bool);
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external returns (bool);
function name() public view returns (string memory);
function currency() public view returns (bytes32);
function userCount() public view returns (uint256);
function userId(address _address) public view returns (uint256);
function validUserId(address _address) public view returns (uint256);
function validUser(address _address, uint256[] memory _keys)
public view returns (uint256, uint256[] memory);
function validity(uint256 _userId) public view returns (uint256, bool);
function extendedKeys() public view returns (uint256[] memory);
function extended(uint256 _userId, uint256 _key)
public view returns (uint256);
function manyExtended(uint256 _userId, uint256[] memory _key)
public view returns (uint256[] memory);
function isAddressValid(address _address) public view returns (bool);
function isValid(uint256 _userId) public view returns (bool);
function defineExtendedKeys(uint256[] memory _extendedKeys) public returns (bool);
function registerUser(address _address, uint256 _validUntilTime)
public returns (bool);
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) public returns (bool);
function attachAddress(uint256 _userId, address _address) public returns (bool);
function detachAddress(address _address) public returns (bool);
function detachSelf() public returns (bool);
function detachSelfAddress(address _address) public returns (bool);
function suspendUser(uint256 _userId) public returns (bool);
function restoreUser(uint256 _userId) public returns (bool);
function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended)
public returns (bool);
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public returns (bool);
function updateUserAllExtended(uint256 _userId, uint256[] memory _values)
public returns (bool);
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) public returns (bool);
}
// File: contracts/tokensale/UserTokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title UserTokensale
* @dev UserTokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
contract UserTokensale is ChangeTokensale {
uint256[] public extendedKeys = [ 0, 1 ]; // KYC Level and AML Limit
// Default investment based on the KYC Level.
// Example [ 0, 300000, 1500000, 10000000, 100000000 ];
uint256[] internal contributionLimits_ = new uint256[](0);
mapping(uint256 => Investor) internal investorIds;
IUserRegistry internal userRegistry_;
/**
* @dev define contributionLimits
*/
function defineContributionLimits(uint256[] memory _contributionLimits)
public onlyOperator returns (bool)
{
contributionLimits_ = _contributionLimits;
emit ContributionLimits(_contributionLimits);
return true;
}
/**
* @dev contributionsLimit
*/
function contributionLimits() public view returns (uint256[] memory) {
return contributionLimits_;
}
/**
* @dev user registry
*/
function userRegistry() public view returns (IUserRegistry) {
return userRegistry_;
}
function registredInvestorUnspentETH(uint256 _investorId)
public view returns (uint256)
{
return investorIds[_investorId].unspentETH;
}
function registredInvestorInvested(uint256 _investorId)
public view returns (uint256)
{
return investorIds[_investorId].invested;
}
function registredInvestorTokens(uint256 _investorId)
public view returns (uint256)
{
return investorIds[_investorId].tokens;
}
function investorCount()
public view returns (uint256)
{
return userRegistry_.userCount();
}
/**
* @dev contributionLimit
*/
function contributionLimit(uint256 _investorId)
public view returns (uint256)
{
uint256 amlLimit = 0;
uint256[] memory extended = userRegistry_.manyExtended(_investorId, extendedKeys);
uint256 kycLevel = extended[0];
uint256 baseAmlLimit = extended[1];
if (baseAmlLimit > 0) {
amlLimit = ratesProvider_.convert(
baseAmlLimit, userRegistry_.currency(), baseCurrency_);
}
if (amlLimit == 0 && kycLevel < contributionLimits_.length) {
amlLimit = contributionLimits_[kycLevel];
}
return amlLimit.sub(investorIds[_investorId].invested);
}
/**
* @dev tokenInvestment
*/
function tokenInvestment(address _investor, uint256 _amount)
public view returns (uint256)
{
uint256 investorId = userRegistry_.validUserId(_investor);
uint256 amlLimit = contributionLimit(investorId);
return super.tokenInvestment(_investor, (_amount < amlLimit) ? _amount : amlLimit);
}
/**
* @dev investor internal
*/
function investorInternal(address _investor)
internal view returns (Investor storage)
{
return investorIds[userRegistry_.userId(_investor)];
}
event ContributionLimits(uint256[] contributionLimits);
}
// File: contracts/Tokensale.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Tokensale
* @dev Tokensale contract
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
contract Tokensale is UserTokensale, BonusTokensale {
/**
* @dev constructor
*/
constructor(
IERC20 _token,
address _vaultERC20,
address payable _vaultETH,
uint256 _tokenPrice,
uint256 _priceUnit,
bytes32 _baseCurrency,
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
uint256 _start,
uint256 _end
) public
BonusTokensale(_token,
_vaultERC20, _vaultETH, _tokenPrice, _priceUnit)
{
baseCurrency_ = _baseCurrency;
userRegistry_ = _userRegistry;
ratesProvider_ = _ratesProvider;
updateSchedule(_start, _end);
}
}
|
withdraw all ETH funds/
|
function withdrawAllETHFunds() public onlyOperator returns (bool) {
uint256 balance = address(this).balance;
withdrawETHInternal(balance);
return true;
}
| 12,886,920
|
// File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingLimiter.sol
pragma solidity 0.4.25;
/**
* @title Wallets Trading Limiter Interface.
*/
interface IWalletsTradingLimiter {
/**
* @dev Increment the limiter value of a wallet.
* @param _wallet The address of the wallet.
* @param _value The amount to be updated.
*/
function updateWallet(address _wallet, uint256 _value) external;
}
// File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingDataSource.sol
pragma solidity 0.4.25;
/**
* @title Wallets Trading Data Source Interface.
*/
interface IWalletsTradingDataSource {
/**
* @dev Increment the value of a given wallet.
* @param _wallet The address of the wallet.
* @param _value The value to increment by.
* @param _limit The limit of the wallet.
*/
function updateWallet(address _wallet, uint256 _value, uint256 _limit) external;
}
// File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingLimiterValueConverter.sol
pragma solidity 0.4.25;
/**
* @title Wallets Trading Limiter Value Converter Interface.
*/
interface IWalletsTradingLimiterValueConverter {
/**
* @dev Get the current limiter currency worth of a given SGA amount.
* @param _sgaAmount The amount of SGA to convert.
* @return The equivalent amount of the limiter currency.
*/
function toLimiterValue(uint256 _sgaAmount) external view returns (uint256);
}
// File: contracts/wallet_trading_limiter/interfaces/ITradingClasses.sol
pragma solidity 0.4.25;
/**
* @title Trading Classes Interface.
*/
interface ITradingClasses {
/**
* @dev Get the limit of a class.
* @param _id The id of the class.
* @return The limit of the class.
*/
function getLimit(uint256 _id) external view returns (uint256);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
pragma solidity 0.4.25;
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address is relates to one of the given identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return Is the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
pragma solidity 0.4.25;
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager";
bytes32 internal constant _ISGAToken_ = "ISGAToken" ;
bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender is relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return Is the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: contracts/authorization/interfaces/IAuthorizationDataSource.sol
pragma solidity 0.4.25;
/**
* @title Authorization Data Source Interface.
*/
interface IAuthorizationDataSource {
/**
* @dev Get the authorized action-role of a wallet.
* @param _wallet The address of the wallet.
* @return The authorized action-role of the wallet.
*/
function getAuthorizedActionRole(address _wallet) external view returns (bool, uint256);
/**
* @dev Get the trade-limit and trade-class of a wallet.
* @param _wallet The address of the wallet.
* @return The trade-limit and trade-class of the wallet.
*/
function getTradeLimitAndClass(address _wallet) external view returns (uint256, uint256);
}
// File: openzeppelin-solidity-v1.12.0/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol
pragma solidity ^0.4.24;
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/wallet_trading_limiter/WalletsTradingLimiterBase.sol
pragma solidity 0.4.25;
/**
* @title Wallets Trading Limiter Base.
*/
contract WalletsTradingLimiterBase is IWalletsTradingLimiter, ContractAddressLocatorHolder, Claimable {
string public constant VERSION = "1.0.0";
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the IAuthorizationDataSource interface.
*/
function getAuthorizationDataSource() public view returns (IAuthorizationDataSource) {
return IAuthorizationDataSource(getContractAddress(_IAuthorizationDataSource_));
}
/**
* @dev Return the contract which implements the IWalletsTradingDataSource interface.
*/
function getWalletsTradingDataSource() public view returns (IWalletsTradingDataSource) {
return IWalletsTradingDataSource(getContractAddress(_IWalletsTradingDataSource_));
}
/**
* @dev Return the contract which implements the IWalletsTradingLimiterValueConverter interface.
*/
function getWalletsTradingLimiterValueConverter() public view returns (IWalletsTradingLimiterValueConverter) {
return IWalletsTradingLimiterValueConverter(getContractAddress(_IWalletsTradingLimiterValueConverter_));
}
/**
* @dev Return the contract which implements the ITradingClasses interface.
*/
function getTradingClasses() public view returns (ITradingClasses) {
return ITradingClasses(getContractAddress(_ITradingClasses_));
}
/**
* @dev Get the limiter value.
* @param _value The amount to be converted to the limiter value.
* @return The limiter value worth of the given amount.
*/
function getLimiterValue(uint256 _value) public view returns (uint256);
/**
* @dev Get the contract locator identifier that is permitted to perform update wallet.
* @return The contract locator identifier.
*/
function getUpdateWalletPermittedContractLocatorIdentifier() public pure returns (bytes32);
/**
* @dev Increment the limiter value of a wallet.
* @param _wallet The address of the wallet.
* @param _value The amount to be updated.
*/
function updateWallet(address _wallet, uint256 _value) external only(getUpdateWalletPermittedContractLocatorIdentifier()) {
uint256 limiterValue = getLimiterValue(_value);
(uint256 tradeLimit, uint256 tradeClass) = getAuthorizationDataSource().getTradeLimitAndClass(_wallet);
uint256 actualLimit = tradeLimit > 0 ? tradeLimit : getTradingClasses().getLimit(tradeClass);
getWalletsTradingDataSource().updateWallet(_wallet, limiterValue, actualLimit);
}
}
// File: contracts/saga-genesis/interfaces/IMintManager.sol
pragma solidity 0.4.25;
/**
* @title Mint Manager Interface.
*/
interface IMintManager {
/**
* @dev Return the current minting-point index.
*/
function getIndex() external view returns (uint256);
}
// File: contracts/saga-genesis/interfaces/ISGNConversionManager.sol
pragma solidity 0.4.25;
/**
* @title SGN Conversion Manager Interface.
*/
interface ISGNConversionManager {
/**
* @dev Compute the SGA worth of a given SGN amount at a given minting-point.
* @param _amount The amount of SGN.
* @param _index The minting-point index.
* @return The equivalent amount of SGA.
*/
function sgn2sga(uint256 _amount, uint256 _index) external view returns (uint256);
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.4.24;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts/saga-genesis/SGNWalletsTradingLimiter.sol
pragma solidity 0.4.25;
/**
* Details of usage of licenced software see here: https://www.saga.org/software/readme_v1
*/
/**
* @title SGN Wallets Trading Limiter.
*/
contract SGNWalletsTradingLimiter is WalletsTradingLimiterBase {
string public constant VERSION = "1.0.0";
using SafeMath for uint256;
using Math for uint256;
/**
* @dev SGN minimum limiter value maximum resolution.
* @notice Allow for sufficiently-high resolution.
* @notice Prevents multiplication-overflow.
*/
uint256 public constant MAX_RESOLUTION = 0x10000000000000000;
uint256 public sequenceNum = 0;
uint256 public sgnMinimumLimiterValueN = 0;
uint256 public sgnMinimumLimiterValueD = 0;
event SGNMinimumLimiterValueSaved(uint256 _sgnMinimumLimiterValueN, uint256 _sgnMinimumLimiterValueD);
event SGNMinimumLimiterValueNotSaved(uint256 _sgnMinimumLimiterValueN, uint256 _sgnMinimumLimiterValueD);
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) WalletsTradingLimiterBase(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the ISGNConversionManager interface.
*/
function getSGNConversionManager() public view returns (ISGNConversionManager) {
return ISGNConversionManager(getContractAddress(_ISGNConversionManager_));
}
/**
* @dev Return the contract which implements the IMintManager interface.
*/
function getMintManager() public view returns (IMintManager) {
return IMintManager(getContractAddress(_IMintManager_));
}
/**
* @dev Get the limiter value.
* @param _value The SGN amount to convert to limiter value.
* @return The limiter value worth of the given SGN amount.
*/
function getLimiterValue(uint256 _value) public view returns (uint256){
uint256 sgnMinimumLimiterValue = calcSGNMinimumLimiterValue(_value);
uint256 sgnConversionValue = calcSGNConversionValue(_value);
return sgnConversionValue.max(sgnMinimumLimiterValue);
}
/**
* @dev Get the contract locator identifier that is permitted to perform update wallet.
* @return The contract locator identifier.
*/
function getUpdateWalletPermittedContractLocatorIdentifier() public pure returns (bytes32){
return _ISGNTokenManager_;
}
/**
* @dev Calculate SGN minimum limiter value.
* @param _sgnAmount The given SGN amount.
* @return The calculated SGN minimum limiter value.
*/
function calcSGNMinimumLimiterValue(uint256 _sgnAmount) public view returns (uint256) {
assert(sgnMinimumLimiterValueN > 0 && sgnMinimumLimiterValueD > 0);
return _sgnAmount.mul(sgnMinimumLimiterValueN) / sgnMinimumLimiterValueD;
}
/**
* @dev Set SGN minimum value.
* @param _sequenceNum The sequence-number of the operation.
* @param _sgnMinimumLimiterValueN The numerator of the SGN minimum limiter value.
* @param _sgnMinimumLimiterValueD The denominator of the SGN minimum limiter value.
*/
function setSGNMinimumLimiterValue(uint256 _sequenceNum, uint256 _sgnMinimumLimiterValueN, uint256 _sgnMinimumLimiterValueD) external onlyOwner {
require(1 <= _sgnMinimumLimiterValueN && _sgnMinimumLimiterValueN <= MAX_RESOLUTION, "SGN minimum limiter value numerator is out of range");
require(1 <= _sgnMinimumLimiterValueD && _sgnMinimumLimiterValueD <= MAX_RESOLUTION, "SGN minimum limiter value denominator is out of range");
if (sequenceNum < _sequenceNum) {
sequenceNum = _sequenceNum;
sgnMinimumLimiterValueN = _sgnMinimumLimiterValueN;
sgnMinimumLimiterValueD = _sgnMinimumLimiterValueD;
emit SGNMinimumLimiterValueSaved(_sgnMinimumLimiterValueN, _sgnMinimumLimiterValueD);
}
else {
emit SGNMinimumLimiterValueNotSaved(_sgnMinimumLimiterValueN, _sgnMinimumLimiterValueD);
}
}
/**
* @dev Calculate SGN conversion value.
* @param _sgnAmount The SGN amount to convert to limiter value.
* @return The limiter value worth of the given SGN.
*/
function calcSGNConversionValue(uint256 _sgnAmount) private view returns (uint256) {
uint256 sgaAmount = getSGNConversionManager().sgn2sga(_sgnAmount, getMintManager().getIndex());
return getWalletsTradingLimiterValueConverter().toLimiterValue(sgaAmount);
}
}
|
Return the contract which implements the IWalletsTradingDataSource interface./
|
function getWalletsTradingDataSource() public view returns (IWalletsTradingDataSource) {
return IWalletsTradingDataSource(getContractAddress(_IWalletsTradingDataSource_));
}
| 5,343,775
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IERC677Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
contract Staking is Ownable, Multicall, IERC677Receiver {
using SafeERC20 for IERC20;
/// @notice Info of each Staking user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of token entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each Staking pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of token to distribute per block.
struct PoolInfo {
uint128 accRewardPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of token contract.
IERC20 public rewardToken;
address public rewardOwner;
/// @notice Info of each Staking pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each Staking pool.
IERC20[] public lpToken;
/// @notice Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public rewardPerBlock = 0;
uint256 private constant ACC_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken);
event LogSetPool(uint256 indexed pid, uint256 allocPoint);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accRewardPerShare);
/// @param _rewardToken The reward token contract address.
constructor(IERC20 _rewardToken, address _rewardOwner, uint256 _rewardPerBlock) public Ownable() {
rewardToken = _rewardToken;
rewardOwner = _rewardOwner;
rewardPerBlock = _rewardPerBlock;
}
/// @notice Sets the reward token.
function setRewardToken(IERC20 _rewardToken) public onlyOwner {
rewardToken = _rewardToken;
}
/// @notice Sets the reward owner.
function setRewardOwner(address _rewardOwner) public onlyOwner {
rewardOwner = _rewardOwner;
}
/// @notice Adjusts the reward per block.
function setRewardsPerBlock(uint256 _rewardPerBlock) public onlyOwner {
rewardPerBlock = _rewardPerBlock;
}
/// @notice Returns the number of Staking pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
function add(uint256 allocPoint, IERC20 _lpToken) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint + allocPoint;
lpToken.push(_lpToken);
poolInfo.push(PoolInfo({
allocPoint: uint64(allocPoint),
lastRewardBlock: uint64(lastRewardBlock),
accRewardPerShare: 0
}));
emit LogPoolAddition(lpToken.length - 1, allocPoint, _lpToken);
}
/// @notice Update the given pool's token allocation point. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
totalAllocPoint = (totalAllocPoint - poolInfo[_pid].allocPoint) + _allocPoint;
poolInfo[_pid].allocPoint = uint64(_allocPoint);
emit LogSetPool(_pid, _allocPoint);
}
/// @notice View function to see pending token reward on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending token reward for a given user.
function pendingRewards(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number - pool.lastRewardBlock;
uint256 reward = (blocks * rewardPerBlock * pool.allocPoint) / totalAllocPoint;
accRewardPerShare = accRewardPerShare + ((reward * ACC_PRECISION) / lpSupply);
}
pending = uint256(int256((user.amount * accRewardPerShare) / ACC_PRECISION) - user.rewardDebt);
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number - pool.lastRewardBlock;
uint256 reward = (blocks * rewardPerBlock * pool.allocPoint) / totalAllocPoint;
pool.accRewardPerShare = pool.accRewardPerShare + uint128((reward * ACC_PRECISION) / lpSupply);
}
pool.lastRewardBlock = uint64(block.number);
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accRewardPerShare);
}
}
/// @notice Deposit LP tokens to Staking for reward token allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount + amount;
user.rewardDebt = user.rewardDebt + int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
// Interactions
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from Staking.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt - int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
user.amount = user.amount - amount;
// Interactions
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of token rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedReward = int256((user.amount * pool.accRewardPerShare) / ACC_PRECISION);
uint256 _pendingReward = uint256(accumulatedReward - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedReward;
// Interactions
if (_pendingReward != 0) {
rewardToken.safeTransferFrom(rewardOwner, to, _pendingReward);
}
emit Harvest(msg.sender, pid, _pendingReward);
}
/// @notice Withdraw LP tokens from Staking and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and token rewards.
function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedReward = int256((user.amount * pool.accRewardPerShare) / ACC_PRECISION);
uint256 _pendingReward = uint256(accumulatedReward - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedReward - int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
user.amount = user.amount - amount;
// Interactions
rewardToken.safeTransferFrom(rewardOwner, to, _pendingReward);
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingReward);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
function onTokenTransfer(address to, uint amount, bytes calldata _data) external override {
uint pid = 0;
require(msg.sender == address(rewardToken), "onTokenTransfer: can only be called by rewardToken");
require(msg.sender == address(lpToken[pid]), "onTokenTransfer: pool 0 needs to be a rewardToken pool");
if (amount > 0) {
// Deposit skipping token transfer (as it already was)
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount + amount;
user.rewardDebt = user.rewardDebt + int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
emit Deposit(msg.sender, pid, amount, to);
}
}
}
|
Harvest proceeds for transaction sender to `to`. pid The index of the pool. See `poolInfo`. to Receiver of token rewards. Effects Interactions
|
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedReward = int256((user.amount * pool.accRewardPerShare) / ACC_PRECISION);
uint256 _pendingReward = uint256(accumulatedReward - user.rewardDebt);
user.rewardDebt = accumulatedReward;
if (_pendingReward != 0) {
rewardToken.safeTransferFrom(rewardOwner, to, _pendingReward);
}
emit Harvest(msg.sender, pid, _pendingReward);
}
| 5,360,074
|
./full_match/3/0x3Dc329b324cDC77aC885740B524F82d066Ca0d0b/sources/stakingOliver/UBXTStaking.sol
|
Call epoch to distribure perf pool ubxt to users this method will call in every 12 hours at fixed time/ This comparison also ensures there is no reentrancy. Snap the Epoch time to the start of this window.
|
function distributePerfPoolRewards() public onlyOwner {
require(inEpochWindow(), "Can not call epoch that time");
require(lastEpochTimestampSec.add(minEpochTimeIntervalSec) < now, "Epoch will call after some time");
uint256 ubxtBal = IERC20(token).balanceOf(perfPool);
IERC20(token).transferFrom(perfPool, address(this), ubxtBal);
epoch = epoch.add(1);
}
| 8,239,108
|
./partial_match/1/0x27BE2e83c3D098625DDF98e687a9353f31646527/sources/contracts/Governor.sol
|
Admin function for setting the proposal threshold newProposalThreshold must be greater than the hardcoded min newProposalThreshold new proposal threshold/
|
function setProposalThreshold(uint256 newProposalThreshold) public {
require(msg.sender == admin, "setProposalThreshold: admin only.");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "_setProposalThreshold: invalid proposal threshold.");
uint256 oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
| 16,092,484
|
pragma solidity =0.6.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./libraries/TransferHelper.sol";
import "./interfaces/IPancakeRouter02.sol";
import "./interfaces/IWETH.sol";
contract FeeReceiver is Pausable, Ownable {
using SafeMath for uint256;
event BuybackRateUpdated(uint256 newBuybackRate);
event RevenueReceiverUpdated(address newRevenueReceiver);
event RouterWhitelistUpdated(address router, bool status);
event BuybackExecuted(uint256 amountBuyback, uint256 amountRevenue);
address internal constant ZERO_ADDRESS = address(0);
uint256 public constant FEE_DENOMINATOR = 10000;
IPancakeRouter02 public pancakeRouter;
address payable public revenueReceiver;
uint256 public buybackRate;
address public SYA;
address public WETH;
mapping(address => bool) public routerWhitelist;
constructor(
IPancakeRouter02 _pancakeRouterV2,
address _SYA,
address _WETH,
address payable _revenueReceiver,
uint256 _buybackRate
) public {
pancakeRouter = _pancakeRouterV2;
SYA = _SYA;
WETH = _WETH;
revenueReceiver = _revenueReceiver;
buybackRate = _buybackRate;
routerWhitelist[address(pancakeRouter)] = true;
}
/// @dev executes the buyback, buys SYA on pancake & sends revenue to the revenueReceiver by the defined rate.
function executeBuyback() external whenNotPaused {
require(address(this).balance > 0, "FeeReceiver: No balance for buyback");
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = SYA;
uint256 balance = address(this).balance;
uint256 amountBuyback = balance.mul(buybackRate).div(FEE_DENOMINATOR);
uint256 amountRevenue = balance.sub(amountBuyback);
pancakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountBuyback}(
0,
path,
ZERO_ADDRESS,
block.timestamp
);
TransferHelper.safeTransferETH(revenueReceiver, amountRevenue);
emit BuybackExecuted(amountBuyback, amountRevenue);
}
/// @dev converts collected tokens from fees to ETH for executing buybacks
function convertToETH(
address _router,
IERC20 _token,
bool _fee
) public whenNotPaused {
require(routerWhitelist[_router], "FeeReceiver: Router not whitelisted");
address[] memory path = new address[](2);
path[0] = address(_token);
path[1] = WETH;
uint256 balance = _token.balanceOf(address(this));
TransferHelper.safeApprove(address(_token), address(pancakeRouter), balance);
if (_fee) {
IPancakeRouter02(_router).swapExactTokensForETHSupportingFeeOnTransferTokens(
balance,
0,
path,
address(this),
block.timestamp
);
} else {
IPancakeRouter02(_router).swapExactTokensForETH(balance, 0, path, address(this), block.timestamp);
}
}
/// @dev converts WETH to ETH
function unwrapWETH() public whenNotPaused {
uint256 balance = IWETH(WETH).balanceOf(address(this));
require(balance > 0, "FeeReceiver: Nothing to unwrap");
IWETH(WETH).withdraw(balance);
}
/// @dev lets the owner update update the router whitelist
function updateRouterWhiteliste(address _router, bool _status) external onlyOwner {
routerWhitelist[_router] = _status;
emit RouterWhitelistUpdated(_router, _status);
}
/// @dev lets the owner update the buyback rate
function updateBuybackRate(uint256 _newBuybackRate) external onlyOwner {
buybackRate = _newBuybackRate;
emit BuybackRateUpdated(_newBuybackRate);
}
/// @dev lets the owner update the revenue receiver address
function updateRevenueReceiver(address payable _newRevenueReceiver) external onlyOwner {
revenueReceiver = _newRevenueReceiver;
emit RevenueReceiverUpdated(_newRevenueReceiver);
}
/// @dev lets the owner withdraw ETH from the contract
function withdrawETH(address payable to, uint256 amount) external onlyOwner {
to.transfer(amount);
}
/// @dev lets the owner withdraw any ERC20 Token from the contract
function withdrawERC20Token(
address token,
address to,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(to, amount);
}
/// @dev allows to receive ETH on this contract
receive() external payable {}
/// @dev lets the owner pause the contract
function pause() external onlyOwner {
_pause();
}
/// @dev lets the owner unpause the contract
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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 Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @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.
*/
abstract 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 virtual 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @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.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity =0.6.6;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
pragma solidity >=0.6.2;
import "./IPancakeRouter01.sol";
interface IPancakeRouter02 is IPancakeRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
function approve(address _spender, uint256 _amount) external returns (bool);
function balanceOf(address _account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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;
}
}
pragma solidity >=0.6.2;
interface IPancakeRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
pragma solidity =0.6.6;
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/PancakeLibrary.sol";
import "./interfaces/IReferralRegistry.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IZerox.sol";
contract FloozRouter is Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using LibBytesV06 for bytes;
event SwapFeeUpdated(uint16 swapFee);
event ReferralRegistryUpdated(address referralRegistry);
event ReferralRewardRateUpdated(uint16 referralRewardRate);
event ReferralsActivatedUpdated(bool activated);
event FeeReceiverUpdated(address payable feeReceiver);
event BalanceThresholdUpdated(uint256 balanceThreshold);
event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate);
event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount);
event ForkUpdated(address factory);
// Denominator of fee
uint256 public constant FEE_DENOMINATOR = 10000;
// Numerator of fee
uint16 public swapFee;
// address of WETH
address public immutable WETH;
// address of zeroEx proxy contract to forward swaps
address payable public immutable zeroEx;
// address of referral registry that stores referral anchors
IReferralRegistry public referralRegistry;
// address of SYA token
IERC20 public saveYourAssetsToken;
// balance threshold of SYA tokens which actives feeless swapping
uint256 public balanceThreshold;
// address that receives protocol fees
address payable public feeReceiver;
// percentage of fees that will be paid as rewards
uint16 public referralRewardRate;
// stores if the referral system is turned on or off
bool public referralsActivated;
// stores individual referral rates
mapping(address => uint16) public customReferralRewardRate;
// stores uniswap forks status, index is the factory address
mapping(address => bool) public forkActivated;
// stores uniswap forks initCodes, index is the factory address
mapping(address => bytes) public forkInitCode;
/// @dev construct this contract
/// @param _WETH address of WETH.
/// @param _swapFee nominator for swapFee. Denominator = 10000
/// @param _referralRewardRate percentage of swapFee that are paid out as rewards
/// @param _feeReceiver address that receives protocol fees
/// @param _balanceThreshold balance threshold of SYA tokens which actives feeless swapping
/// @param _saveYourAssetsToken address of SYA token
/// @param _referralRegistry address of referral registry that stores referral anchors
/// @param _zeroEx address of zeroX proxy contract to forward swaps
constructor(
address _WETH,
uint16 _swapFee,
uint16 _referralRewardRate,
address payable _feeReceiver,
uint256 _balanceThreshold,
IERC20 _saveYourAssetsToken,
IReferralRegistry _referralRegistry,
address payable _zeroEx
) public {
WETH = _WETH;
swapFee = _swapFee;
referralRewardRate = _referralRewardRate;
feeReceiver = _feeReceiver;
saveYourAssetsToken = _saveYourAssetsToken;
balanceThreshold = _balanceThreshold;
referralRegistry = _referralRegistry;
zeroEx = _zeroEx;
referralsActivated = true;
}
/// @dev execute swap directly on Uniswap/Pancake & simular forks
/// @param fork fork used to execute swap
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
/// @return amounts
function swapExactETHForTokens(
address fork,
uint256 amountOutMin,
address[] calldata path,
address referee
) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) {
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
referee = _getReferee(referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
msg.value,
referee,
false
);
amounts = _getAmountsOut(fork, swapAmount, path);
require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), amounts[0]));
_swap(fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountIn amount of tokensIn
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
function swapExactTokensForETHSupportingFeeOnTransferTokens(
address fork,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address referee
) external whenNotPaused isValidFork(fork) isValidReferee(referee) {
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
referee = _getReferee(referee);
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amountIn);
_swapSupportingFeeOnTransferTokens(fork, path, address(this));
uint256 amountOut = IERC20(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(amountOut);
(uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
amountOut,
referee,
false
);
require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE");
TransferHelper.safeTransferETH(msg.sender, amountWithdraw);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
/// @return amounts
function swapExactTokensForTokens(
address fork,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address referee
) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) {
referee = _getReferee(referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
amountIn,
referee,
false
);
amounts = _getAmountsOut(fork, swapAmount, path);
require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), swapAmount);
_swap(fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
/// @return amounts
function swapExactTokensForETH(
address fork,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address referee
) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
referee = _getReferee(referee);
amounts = _getAmountsOut(fork, amountIn, path);
(uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
amounts[amounts.length - 1],
referee,
false
);
require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]);
_swap(fork, amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(msg.sender, amountWithdraw);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountOut expected amount of tokens out
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
/// @return amounts
function swapETHForExactTokens(
address fork,
uint256 amountOut,
address[] calldata path,
address referee
) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) {
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
amounts = _getAmountsIn(fork, amountOut, path);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amounts[0], referee, true);
require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), amounts[0]));
_swap(fork, amounts, path, msg.sender);
// refund dust eth, if any
if (msg.value > amounts[0].add(feeAmount).add(referralReward))
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward));
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
address fork,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address referee
) external whenNotPaused isValidFork(fork) isValidReferee(referee) {
referee = _getReferee(referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
amountIn,
referee,
false
);
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), swapAmount);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountOut expected tokens to receive
/// @param amountInMax maximum tokens to send
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
/// @return amounts
function swapTokensForExactTokens(
address fork,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address referee
) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) {
referee = _getReferee(referee);
amounts = _getAmountsIn(fork, amountOut, path);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amounts[0], referee, true);
require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]);
_swap(fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountOut expected tokens to receive
/// @param amountInMax maximum tokens to send
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
/// @return amounts
function swapTokensForExactETH(
address fork,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address referee
) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
referee = _getReferee(referee);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amountOut, referee, true);
amounts = _getAmountsIn(fork, amountOut.add(feeAmount).add(referralReward), path);
require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]);
_swap(fork, amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(msg.sender, amountOut);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param fork fork used to execute swap
/// @param amountOutMin minimum expected tokens to receive
/// @param path Sell path.
/// @param referee address of referee for msg.sender, 0x adress if none
function swapExactETHForTokensSupportingFeeOnTransferTokens(
address fork,
uint256 amountOutMin,
address[] calldata path,
address referee
) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) {
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
referee = _getReferee(referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
msg.value,
referee,
false
);
IWETH(WETH).deposit{value: swapAmount}();
assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), swapAmount));
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev returns the referee for a given address, if new, registers referee
/// @param referee the address of the referee for msg.sender
/// @return referee address from referral registry
function _getReferee(address referee) internal returns (address) {
address sender = msg.sender;
if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) {
referralRegistry.createReferralAnchor(sender, referee);
}
return referralRegistry.getUserReferee(sender);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
address fork,
uint256[] memory amounts,
address[] memory path,
address _to
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to;
IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address fork,
address[] memory path,
address _to
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
IPancakePair pair = IPancakePair(_pairFor(fork, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
/// @dev Fallback function to execute swaps directly on 0x for users that don't pay a fee
/// @dev params as of API documentation from 0x API (https://0x.org/docs/api#response-1)
fallback() external payable {
require(userAboveBalanceThreshold(msg.sender), "FloozRouter: FORBIDDEN");
bytes4 selector = msg.data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
(bool success, ) = impl.delegatecall(msg.data);
require(success, "FloozRouter: REVERTED");
}
/// @dev Executes a swap on 0x API
/// @param data calldata expected by data field on 0x API (https://0x.org/docs/api#response-1)
/// @param tokenOut the address of currency to sell – 0x address for ETH
/// @param tokenIn the address of currency to buy – 0x address for ETH
/// @param referee address of referee for msg.sender, 0x adress if none
function executeZeroExSwap(
bytes calldata data,
address tokenOut,
address tokenIn,
address referee
) external payable nonReentrant whenNotPaused isValidReferee(referee) {
referee = _getReferee(referee);
bytes4 selector = data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
bool isAboveThreshold = userAboveBalanceThreshold(msg.sender);
// skip fees & rewards for god mode users
if (isAboveThreshold) {
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
} else {
// if ETH in execute trade as router & distribute funds & fees
if (msg.value > 0) {
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
msg.value,
referee,
false
);
(bool success, ) = impl.call{value: swapAmount}(data);
require(success, "FloozRouter: REVERTED");
TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this)));
_withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward);
} else {
uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender);
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender);
require(balanceBefore > balanceAfter, "INVALID_TOKEN");
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
balanceBefore.sub(balanceAfter),
referee,
true
);
_withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward);
}
}
}
/// @dev calculates swap, fee & reward amounts
/// @param amount total amount of tokens
/// @param referee the address of the referee for msg.sender
function _calculateFeesAndRewards(
uint256 amount,
address referee,
bool additiveFee
)
internal
view
returns (
uint256 swapAmount,
uint256 feeAmount,
uint256 referralReward
)
{
// no fees for users above threshold
if (userAboveBalanceThreshold(msg.sender)) {
swapAmount = amount;
} else {
if (additiveFee) {
swapAmount = amount;
feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount);
} else {
feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR);
swapAmount = amount.sub(feeAmount);
}
// calculate referral rates, if referee is not 0x
if (referee != address(0) && referralsActivated) {
uint16 referralRate = customReferralRewardRate[referee] > 0
? customReferralRewardRate[referee]
: referralRewardRate;
referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR);
feeAmount = feeAmount.sub(referralReward);
} else {
referralReward = 0;
}
}
}
/// @dev lets the admin update an Uniswap style fork
function updateFork(
address _factory,
bytes calldata _initCode,
bool _activated
) external onlyOwner {
forkActivated[_factory] = _activated;
forkInitCode[_factory] = _initCode;
emit ForkUpdated(_factory);
}
/// @dev returns if a users is above the SYA threshold and can swap without fees
function userAboveBalanceThreshold(address _account) public view returns (bool) {
return saveYourAssetsToken.balanceOf(_account) >= balanceThreshold;
}
/// @dev returns the fee nominator for a given user
function getUserFee(address user) public view returns (uint256) {
saveYourAssetsToken.balanceOf(user) >= balanceThreshold ? 0 : swapFee;
}
/// @dev lets the admin update the swapFee nominator
function updateSwapFee(uint16 newSwapFee) external onlyOwner {
swapFee = newSwapFee;
emit SwapFeeUpdated(newSwapFee);
}
/// @dev lets the admin update the referral reward rate
function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner {
require(newReferralRewardRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE");
referralRewardRate = newReferralRewardRate;
emit ReferralRewardRateUpdated(newReferralRewardRate);
}
/// @dev lets the admin update which address receives the protocol fees
function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner {
feeReceiver = newFeeReceiver;
emit FeeReceiverUpdated(newFeeReceiver);
}
/// @dev lets the admin update the SYA balance threshold, which activates feeless trading for users
function updateBalanceThreshold(uint256 newBalanceThreshold) external onlyOwner {
balanceThreshold = newBalanceThreshold;
emit BalanceThresholdUpdated(balanceThreshold);
}
/// @dev lets the admin update the status of the referral system
function updateReferralsActivated(bool newReferralsActivated) external onlyOwner {
referralsActivated = newReferralsActivated;
emit ReferralsActivatedUpdated(newReferralsActivated);
}
/// @dev lets the admin set a new referral registry
function updateReferralRegistry(address newReferralRegistry) external onlyOwner {
referralRegistry = IReferralRegistry(newReferralRegistry);
emit ReferralRegistryUpdated(newReferralRegistry);
}
/// @dev lets the admin set a custom referral rate
function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) {
require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE");
customReferralRewardRate[account] = referralRate;
emit CustomReferralRewardRateUpdated(account, referralRate);
}
/// @dev returns the referee for a given user – 0x address if none
function getUserReferee(address user) external view returns (address) {
return referralRegistry.getUserReferee(user);
}
/// @dev returns if the given user has been referred or not
function hasUserReferee(address user) external view returns (bool) {
return referralRegistry.hasUserReferee(user);
}
/// @dev lets the admin withdraw ETH from the contract.
function withdrawETH(address payable to, uint256 amount) external onlyOwner {
TransferHelper.safeTransferETH(to, amount);
}
/// @dev lets the admin withdraw ERC20s from the contract.
function withdrawERC20Token(
address token,
address to,
uint256 amount
) external onlyOwner {
TransferHelper.safeTransfer(token, to, amount);
}
/// @dev distributes fees & referral rewards to users
function _withdrawFeesAndRewards(
address tokenReward,
address tokenOut,
address referee,
uint256 feeAmount,
uint256 referralReward
) internal {
if (tokenReward == address(0)) {
TransferHelper.safeTransferETH(feeReceiver, feeAmount);
if (referralReward > 0) {
TransferHelper.safeTransferETH(referee, referralReward);
emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward);
}
} else {
TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount);
if (referralReward > 0) {
TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward);
emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward);
}
}
}
/// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function _getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul((9980));
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(10000).add(amountInWithFee);
amountOut = numerator / denominator;
}
/// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function _getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(10000);
uint256 denominator = reserveOut.sub(amountOut).mul(9980);
amountIn = (numerator / denominator).add(1);
}
/// @dev performs chained getAmountOut calculations on any number of pairs
function _getAmountsOut(
address fork,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "FloozRouter: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]);
amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
/// @dev performs chained getAmountIn calculations on any number of pairs
function _getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "FloozRouter: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
/// @dev fetches and sorts the reserves for a pair
function _getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
/// @dev calculates the CREATE2 address for a pair without making any external calls
function _pairFor(
address factory,
address tokenA,
address tokenB
) internal view returns (address pair) {
(address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
forkInitCode[factory] // init code hash
)
)
)
);
}
/// @dev lets the admin pause this contract
function pause() external onlyOwner {
_pause();
}
/// @dev lets the admin unpause this contract
function unpause() external onlyOwner {
_unpause();
}
/// @dev allows to receive ETH on the contract
receive() external payable {}
modifier isValidFork(address factory) {
require(forkActivated[factory], "FloozRouter: INVALID_FACTORY");
_;
}
modifier isValidReferee(address referee) {
require(msg.sender != referee, "FloozRouter: SELF_REFERRAL");
_;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./errors/LibBytesRichErrorsV06.sol";
import "./errors/LibRichErrorsV06.sol";
library LibBytesV06 {
using LibBytesV06 for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// When `from == 0`, the original array will match the slice.
/// In other cases its state will be corrupted.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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].
*/
abstract 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;
}
}
pragma solidity =0.6.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface IPancakePair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library PancakeLibrary {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "PancakeLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "PancakeLibrary: ZERO_ADDRESS");
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "PancakeLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "PancakeLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
}
pragma solidity >=0.5.0;
interface IReferralRegistry {
function getUserReferee(address _user) external view returns (address);
function hasUserReferee(address _user) external view returns (bool);
function createReferralAnchor(address _user, address _referee) external;
}
pragma solidity ^0.6.5;
interface IZerox {
function getFunctionImplementation(bytes4 selector) external returns (address payable);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibBytesRichErrorsV06 {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
pragma solidity =0.6.6;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/PancakeLibrary.sol";
import "./interfaces/IReferralRegistry.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IZerox.sol";
contract TestMultichainRouter is Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using LibBytesV06 for bytes;
event SwapFeeUpdated(uint16 swapFee);
event ReferralRegistryUpdated(address referralRegistry);
event ReferralRewardRateUpdated(uint16 referralRewardRate);
event ReferralsActivatedUpdated(bool activated);
event FeeReceiverUpdated(address payable feeReceiver);
event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate);
event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount);
event ForkCreated(address factory);
event ForkUpdated(address factory);
struct SwapData {
address fork;
address referee;
bool fee;
}
// Denominator of fee
uint256 public constant FEE_DENOMINATOR = 10000;
// Numerator of fee
uint16 public swapFee;
// address of WETH
address public immutable WETH;
// address of zeroEx proxy contract to forward swaps
address payable public immutable zeroEx;
// address of referral registry that stores referral anchors
IReferralRegistry public referralRegistry;
// address that receives protocol fees
address payable public feeReceiver;
// percentage of fees that will be paid as rewards
uint16 public referralRewardRate;
// stores if the referral system is turned on or off
bool public referralsActivated;
// stores individual referral rates
mapping(address => uint16) public customReferralRewardRate;
// stores uniswap forks status, index is the factory address
mapping(address => bool) public forkActivated;
// stores uniswap forks initCodes, index is the factory address
mapping(address => bytes) public forkInitCode;
/// @dev construct this contract
/// @param _WETH address of WETH.
/// @param _swapFee nominator for swapFee. Denominator = 10000
/// @param _referralRewardRate percentage of swapFee that are paid out as rewards
/// @param _feeReceiver address that receives protocol fees
/// @param _referralRegistry address of referral registry that stores referral anchors
/// @param _zeroEx address of zeroX proxy contract to forward swaps
constructor(
address _WETH,
uint16 _swapFee,
uint16 _referralRewardRate,
address payable _feeReceiver,
IReferralRegistry _referralRegistry,
address payable _zeroEx
) public {
WETH = _WETH;
swapFee = _swapFee;
referralRewardRate = _referralRewardRate;
feeReceiver = _feeReceiver;
referralRegistry = _referralRegistry;
zeroEx = _zeroEx;
referralsActivated = true;
}
/// @dev execute swap directly on Uniswap/Pancake & simular forks
/// @param swapData stores the swapData information
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @return amounts
function swapExactETHForTokens(
SwapData calldata swapData,
uint256 amountOutMin,
address[] calldata path
)
external
payable
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
msg.value,
referee,
false
);
amounts = _getAmountsOut(swapData.fork, swapAmount, path);
require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0]));
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount of tokensIn
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
function swapExactTokensForETHSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amountIn);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, address(this));
uint256 amountOut = IERC20(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(amountOut);
(uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountOut,
referee,
false
);
require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE");
TransferHelper.safeTransferETH(msg.sender, amountWithdraw);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @return amounts
function swapExactTokensForTokens(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountIn,
referee,
false
);
amounts = _getAmountsOut(swapData.fork, swapAmount, path);
require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount);
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
/// @return amounts
function swapExactTokensForETH(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
amounts = _getAmountsOut(swapData.fork, amountIn, path);
(uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amounts[amounts.length - 1],
referee,
false
);
require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]);
_swap(swapData.fork, amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(msg.sender, amountWithdraw);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOut expected amount of tokens out
/// @param path Sell path.
/// @return amounts
function swapETHForExactTokens(
SwapData calldata swapData,
uint256 amountOut,
address[] calldata path
)
external
payable
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
amounts = _getAmountsIn(swapData.fork, amountOut, path);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amounts[0],
referee,
true
);
require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0]));
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
// refund dust eth, if any
if (msg.value > amounts[0].add(feeAmount).add(referralReward))
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward));
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountIn amount if tokens In
/// @param amountOutMin minimum tokens to receive
/// @param path Sell path.
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountIn,
referee,
false
);
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOut expected tokens to receive
/// @param amountInMax maximum tokens to send
/// @param path Sell path.
/// @return amounts
function swapTokensForExactTokens(
SwapData calldata swapData,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
address referee = _getReferee(swapData.referee);
amounts = _getAmountsIn(swapData.fork, amountOut, path);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amounts[0],
referee,
true
);
require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]);
_swap(swapData.fork, amounts, path, msg.sender);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOut expected tokens to receive
/// @param amountInMax maximum tokens to send
/// @param path Sell path.
/// @return amounts
function swapTokensForExactETH(
SwapData calldata swapData,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path
)
external
whenNotPaused
isValidFork(swapData.fork)
isValidReferee(swapData.referee)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
amountOut,
referee,
true
);
amounts = _getAmountsIn(swapData.fork, amountOut.add(feeAmount).add(referralReward), path);
require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]);
_swap(swapData.fork, amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(msg.sender, amountOut);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev execute swap directly on Uniswap/Pancake/...
/// @param swapData stores the swapData information
/// @param amountOutMin minimum expected tokens to receive
/// @param path Sell path.
function swapExactETHForTokensSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountOutMin,
address[] calldata path
) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
msg.value,
referee,
false
);
IWETH(WETH).deposit{value: swapAmount}();
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), swapAmount));
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
/// @dev returns the referee for a given address, if new, registers referee
/// @param referee the address of the referee for msg.sender
/// @return referee address from referral registry
function _getReferee(address referee) internal returns (address) {
address sender = msg.sender;
if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) {
referralRegistry.createReferralAnchor(sender, referee);
}
return referralRegistry.getUserReferee(sender);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
address fork,
uint256[] memory amounts,
address[] memory path,
address _to
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to;
IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address fork,
address[] memory path,
address _to
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
IPancakePair pair = IPancakePair(_pairFor(fork, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
/// @dev Fallback function to execute swaps directly on 0x for users that don't pay a fee
/// @dev params as of API documentation from 0x API (https://0x.org/docs/api#response-1)
fallback() external payable {
bytes4 selector = msg.data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
(bool success, ) = impl.delegatecall(msg.data);
require(success, "FloozRouter: REVERTED");
}
/// @dev Executes a swap on 0x API
/// @param data calldata expected by data field on 0x API (https://0x.org/docs/api#response-1)
/// @param tokenOut the address of currency to sell - 0x address for ETH
/// @param tokenIn the address of currency to buy - 0x address for ETH
/// @param referee address of referee for msg.sender, 0x adress if none
/// @param fee boolean if fee should be applied or not
function executeZeroExSwap(
bytes calldata data,
address tokenOut,
address tokenIn,
address referee,
bool fee
) external payable nonReentrant whenNotPaused isValidReferee(referee) {
referee = _getReferee(referee);
bytes4 selector = data.readBytes4(0);
address impl = IZerox(zeroEx).getFunctionImplementation(selector);
require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION");
if (!fee) {
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
} else {
// if ETH in execute trade as router & distribute funds & fees
if (msg.value > 0) {
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
fee,
msg.value,
referee,
false
);
_withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward);
(bool success, ) = impl.call{value: swapAmount}(data);
require(success, "FloozRouter: REVERTED");
TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this)));
} else {
uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender);
(bool success, ) = impl.delegatecall(data);
require(success, "FloozRouter: REVERTED");
uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender);
require(balanceBefore > balanceAfter, "INVALID_TOKEN");
(, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
fee,
balanceBefore.sub(balanceAfter),
referee,
true
);
_withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward);
}
}
}
/// @dev calculates swap, fee & reward amounts
/// @param fee boolean if fee will be applied or not
/// @param amount total amount of tokens
/// @param referee the address of the referee for msg.sender
function _calculateFeesAndRewards(
bool fee,
uint256 amount,
address referee,
bool additiveFee
)
internal
view
returns (
uint256 swapAmount,
uint256 feeAmount,
uint256 referralReward
)
{
// no fees for users above threshold
if (!fee) {
swapAmount = amount;
} else {
if (additiveFee) {
swapAmount = amount;
feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount);
} else {
feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR);
swapAmount = amount.sub(feeAmount);
}
// calculate referral rates, if referee is not 0x
if (referee != address(0) && referralsActivated) {
uint16 referralRate = customReferralRewardRate[referee] > 0
? customReferralRewardRate[referee]
: referralRewardRate;
referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR);
feeAmount = feeAmount.sub(referralReward);
} else {
referralReward = 0;
}
}
}
/// @dev lets the admin register an Uniswap style fork
function registerFork(address _factory, bytes calldata _initCode) external onlyOwner {
require(!forkActivated[_factory], "FloozRouter: ACTIVE_FORK");
forkActivated[_factory] = true;
forkInitCode[_factory] = _initCode;
emit ForkCreated(_factory);
}
/// @dev lets the admin update an Uniswap style fork
function updateFork(
address _factory,
bytes calldata _initCode,
bool _activated
) external onlyOwner {
forkActivated[_factory] = _activated;
forkInitCode[_factory] = _initCode;
emit ForkUpdated(_factory);
}
/// @dev lets the admin update the swapFee nominator
function updateSwapFee(uint16 newSwapFee) external onlyOwner {
swapFee = newSwapFee;
emit SwapFeeUpdated(newSwapFee);
}
/// @dev lets the admin update the referral reward rate
function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner {
referralRewardRate = newReferralRewardRate;
emit ReferralRewardRateUpdated(newReferralRewardRate);
}
/// @dev lets the admin update which address receives the protocol fees
function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner {
feeReceiver = newFeeReceiver;
emit FeeReceiverUpdated(newFeeReceiver);
}
/// @dev lets the admin update the status of the referral system
function updateReferralsActivated(bool newReferralsActivated) external onlyOwner {
referralsActivated = newReferralsActivated;
emit ReferralsActivatedUpdated(newReferralsActivated);
}
/// @dev lets the admin set a new referral registry
function updateReferralRegistry(address newReferralRegistry) external onlyOwner {
referralRegistry = IReferralRegistry(newReferralRegistry);
emit ReferralRegistryUpdated(newReferralRegistry);
}
/// @dev lets the admin set a custom referral rate
function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) {
require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE");
customReferralRewardRate[account] = referralRate;
emit CustomReferralRewardRateUpdated(account, referralRate);
}
/// @dev returns the referee for a given user - 0x address if none
function getUserReferee(address user) external view returns (address) {
return referralRegistry.getUserReferee(user);
}
/// @dev returns if the given user has been referred or not
function hasUserReferee(address user) external view returns (bool) {
return referralRegistry.hasUserReferee(user);
}
/// @dev lets the admin withdraw ETH from the contract.
function withdrawETH(address payable to, uint256 amount) external onlyOwner {
TransferHelper.safeTransferETH(to, amount);
}
/// @dev lets the admin withdraw ERC20s from the contract.
function withdrawERC20Token(
address token,
address to,
uint256 amount
) external onlyOwner {
TransferHelper.safeTransfer(token, to, amount);
}
/// @dev distributes fees & referral rewards to users
function _withdrawFeesAndRewards(
address tokenReward,
address tokenOut,
address referee,
uint256 feeAmount,
uint256 referralReward
) internal {
if (tokenReward == address(0)) {
TransferHelper.safeTransferETH(feeReceiver, feeAmount);
if (referralReward > 0) {
TransferHelper.safeTransferETH(referee, referralReward);
emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward);
}
} else {
TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount);
if (referralReward > 0) {
TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward);
emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward);
}
}
}
/// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function _getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul((9975));
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(10000).add(amountInWithFee);
amountOut = numerator / denominator;
}
/// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function _getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(10000);
uint256 denominator = reserveOut.sub(amountOut).mul(9975);
amountIn = (numerator / denominator).add(1);
}
/// @dev performs chained getAmountOut calculations on any number of pairs
function _getAmountsOut(
address fork,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "FloozRouter: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]);
amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
/// @dev performs chained getAmountIn calculations on any number of pairs
function _getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "FloozRouter: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
/// @dev fetches and sorts the reserves for a pair
function _getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
/// @dev calculates the CREATE2 address for a pair without making any external calls
function _pairFor(
address factory,
address tokenA,
address tokenB
) internal view returns (address pair) {
(address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
forkInitCode[factory] // init code hash
)
)
)
);
}
/// @dev lets the admin pause this contract
function pause() external onlyOwner {
_pause();
}
/// @dev lets the admin unpause this contract
function unpause() external onlyOwner {
_unpause();
}
/// @dev allows to receive ETH on the contract
receive() external payable {}
modifier isValidFork(address factory) {
require(forkActivated[factory], "FloozRouter: INVALID_FACTORY");
_;
}
modifier isValidReferee(address referee) {
require(msg.sender != referee, "FloozRouter: SELF_REFERRAL");
_;
}
}
pragma solidity =0.6.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/TransferHelper.sol";
import "./interfaces/IWETH.sol";
contract FeeReceiverMultichain is Ownable {
address public WETH;
constructor(address _WETH) public {
WETH = _WETH;
}
/// @dev converts WETH to ETH
function unwrapWETH() public {
uint256 balance = IWETH(WETH).balanceOf(address(this));
require(balance > 0, "FeeReceiver: Nothing to unwrap");
IWETH(WETH).withdraw(balance);
}
/// @dev lets the owner withdraw ETH from the contract
function withdrawETH(address payable to, uint256 amount) external onlyOwner {
to.transfer(amount);
}
/// @dev lets the owner withdraw any ERC20 Token from the contract
function withdrawERC20Token(
address token,
address to,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(to, amount);
}
/// @dev allows to receive ETH on this contract
receive() external payable {}
}
pragma solidity =0.6.6;
import "@openzeppelin/contracts/access/Ownable.sol";
contract ReferralRegistry is Ownable {
event ReferralAnchorCreated(address indexed user, address indexed referee);
event ReferralAnchorUpdated(address indexed user, address indexed referee);
event AnchorManagerUpdated(address account, bool isManager);
// stores addresses which are allowed to create new anchors
mapping(address => bool) public isAnchorManager;
// stores the address that referred a given user
mapping(address => address) public referralAnchor;
/// @dev create a new referral anchor on the registry
/// @param _user address of the user
/// @param _referee address wich referred the user
function createReferralAnchor(address _user, address _referee) external onlyAnchorManager {
require(referralAnchor[_user] == address(0), "ReferralRegistry: ANCHOR_EXISTS");
referralAnchor[_user] = _referee;
emit ReferralAnchorCreated(_user, _referee);
}
/// @dev allows admin to overwrite anchor
/// @param _user address of the user
/// @param _referee address wich referred the user
function updateReferralAnchor(address _user, address _referee) external onlyOwner {
referralAnchor[_user] = _referee;
emit ReferralAnchorUpdated(_user, _referee);
}
/// @dev allows admin to grant/remove anchor priviliges
/// @param _anchorManager address of the anchor manager
/// @param _isManager add or remove privileges
function updateAnchorManager(address _anchorManager, bool _isManager) external onlyOwner {
isAnchorManager[_anchorManager] = _isManager;
emit AnchorManagerUpdated(_anchorManager, _isManager);
}
function getUserReferee(address _user) external view returns (address) {
return referralAnchor[_user];
}
function hasUserReferee(address _user) external view returns (bool) {
return referralAnchor[_user] != address(0);
}
modifier onlyAnchorManager() {
require(isAnchorManager[msg.sender], "ReferralRegistry: FORBIDDEN");
_;
}
}
|
execute swap directly on Uniswap/Pancake/... swapData stores the swapData information amountOutMin minimum expected tokens to receive path Sell path.
|
function swapExactETHForTokensSupportingFeeOnTransferTokens(
SwapData calldata swapData,
uint256 amountOutMin,
address[] calldata path
) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) {
require(path[0] == WETH, "FloozRouter: INVALID_PATH");
address referee = _getReferee(swapData.referee);
(uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(
swapData.fee,
msg.value,
referee,
false
);
assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), swapAmount));
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender);
_swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender);
require(
IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin,
"FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
if (feeAmount.add(referralReward) > 0)
_withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward);
}
| 600,862
|
./full_match/1/0x6f737614cC5b89bbAd665f0e6803eE6867835d58/sources/contracts/CErc20AuraDelegator.sol
|
Accrue interest then return the up-to-date exchange rate return Calculated exchange rate scaled by 1e18/
|
function exchangeRateCurrent() override public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("exchangeRateCurrent()"));
return abi.decode(data, (uint));
}
| 3,001,933
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract TextModule {
event TextDelivered(address user,string tofro); // Event
mapping (address => string) toCreator;
mapping (address => string) fromCreator;
address TEXTowner;
constructor() {
TEXTowner=msg.sender;
}
function ownerReads() public view returns (string memory txt) {
//if (balanceOf(msg.sender)>0){
return fromCreator[msg.sender];
//}
//return "none";
}
function creatorReads(address user) public view returns (string memory txt) {
if (TEXTowner==msg.sender){
return toCreator[user];
}
return "none";
}
function ownerWrites(string memory txt) public {
//address(this)
//if (balanceOf(msg.sender)>0){
toCreator[msg.sender] = txt;
emit TextDelivered(TEXTowner,'to'); // Triggering event
//}
}
function creatorWrites(address user,string memory txt) public {
if (TEXTowner==msg.sender){
fromCreator[user] = txt;
emit TextDelivered(user,'from'); // Triggering event
}
}
function TEXTgetVersion() public pure returns (string memory version) {
return "TextModule v 0.0.2";
}
}
|
address(this)if (balanceOf(msg.sender)>0){}
|
function ownerWrites(string memory txt) public {
toCreator[msg.sender] = txt;
}
| 14,125,043
|
./full_match/80001/0x139A67ABdAb91a0d54aD3b6fC9AF46c1457667E2/sources/contracts/User.sol
|
Check if user already exists require(users[_user].address == address(0), "User already exists"); Store user address in nameToAddress mapping
|
function createUser(address _user, string memory _role, string memory _name) public {
require(_user != address(0), "User address can't be zero");
require(bytes(_role).length > 0, "Role can't be empty");
require(bytes(_name).length > 0, "Name can't be empty");
Role role = new Role();
users[_user] = UserStruct(_name, _role);
role.setRole(_user, _role);
nameToAddress[_name] = _user;
emit UserCreated(_user, _role, _name);
}
| 5,589,729
|
./full_match/56/0xBbD8Cb37Fa7eBCc6081d1785784C9E15c8903A2E/sources/BEP20Mintable.sol
|
Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {BEP20-_burn} and {BEP20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./
|
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
| 3,236,759
|
// SPDX-License-Identifier: MIT
// CREDIT: https://github.com/alexanvl/bloccwarz/blob/master/contracts/BloccWarz.sol
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../token/ERC20/CollabLandERC20Mintable.sol";
contract BondingCurve is CollabLandERC20Mintable {
using SafeMath for uint256;
address payable public owner;
bool public halted;
uint256 public poolBalance = 0;
uint256 public minTokenTransactionWei = 400; // enforce a minimum purchase/sale amount
uint256 public transactionFeeAs1PctDenom = 4; // used to keep fee calculations as integers
uint256 public tokenBWCWeiLockup = 1e21; // 1000 tokens will stay locked in the contract
constructor(string memory _name, string memory _symbol)
CollabLandERC20Mintable(_name, _symbol)
{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function previewBuy(uint256 value) public view returns (uint256, uint256) {
// Calculate fee as a fraction of 1%
uint256 feeWei =
SafeMath.div(SafeMath.div(value, 100), transactionFeeAs1PctDenom);
uint256 purchaseWei = SafeMath.sub(value, feeWei);
// Determine how many tokens to be minted
// f(x) = 0.001x
// F(x) = (x^2)/2000 + C
// purchaseWei = ((totalSupply() + tokensMinted)^2)/2000 - poolBalance
// tokensMinted = sqrt(2000 * (purchaseWei + poolBalance)) - totalSupply()
uint256 tokensMinted =
SafeMath.sub(
sqrt(
SafeMath.mul(2000, SafeMath.add(purchaseWei, poolBalance))
),
totalSupply()
);
return (tokensMinted, purchaseWei);
}
function buyTokens() public payable {
// Purchase must be enough wei for contract to collect fee
require(
msg.value >= minTokenTransactionWei,
"Must send minimum transaction amount to buy tokens"
);
(uint256 tokensMinted, uint256 purchaseWei) = previewBuy(msg.value);
// mint tokens for sender
_mint(msg.sender, tokensMinted);
// incerement pool balance
poolBalance = SafeMath.add(poolBalance, purchaseWei);
}
function previewSell(uint256 _tokensBWCWei) public view returns (uint256) {
require(
_tokensBWCWei > 0,
"Token amount for sale must be greater than 0"
);
// Calculate wei value of tokens for sale
// f(x) = 0.001x
// F(x) = (x^2)/2000 + C
// salePriceWei = poolBalance - ((totalSupply() - _tokensBWCWei)^2)/2000
uint256 targetTokenSupply = SafeMath.sub(totalSupply(), _tokensBWCWei);
uint256 salePriceWei =
SafeMath.sub(
poolBalance,
SafeMath.div(
SafeMath.mul(targetTokenSupply, targetTokenSupply),
2000
)
);
require(
salePriceWei >= minTokenTransactionWei,
"Token sale value must meet minimum transaction amount"
);
// This should be impossible to trigger
// require(poolBalance >= salePriceWei, "Contract balance insufficient for sale");
// Calculate fee as a fraction of 1% of sale price
uint256 feeWei =
SafeMath.div(
SafeMath.div(salePriceWei, 100),
transactionFeeAs1PctDenom
);
uint256 sellerBalanceWei = SafeMath.sub(salePriceWei, feeWei);
return sellerBalanceWei;
}
function sellTokens(uint256 _tokensBWCWei) public payable {
uint256 sellerBalanceWei = previewSell(_tokensBWCWei);
// transfer the tokens
require(
transferFrom(msg.sender, address(this), _tokensBWCWei),
"ERC-20 transferFrom failed"
);
// Burn tokens
_burn(msg.sender, _tokensBWCWei);
// Pay seller
msg.sender.transfer(sellerBalanceWei);
// update pool balance
poolBalance = SafeMath.sub(poolBalance, sellerBalanceWei);
}
function withdrawWei(uint256 _amountWei) public onlyOwner {
// Owner can never take from the pool, only contract profits
require(
_amountWei <= SafeMath.sub(address(this).balance, poolBalance),
"Withdraw exceeds limit"
);
owner.transfer(_amountWei);
}
function withdrawTokens(uint256 _tokensBWCWei) public onlyOwner {
// Owner can withdraw tokens collected by the contract above the lockup amount
require(
balanceOf(address(this)) > tokenBWCWeiLockup,
"Not enough tokens locked up"
);
_transfer(msg.sender, owner, _tokensBWCWei);
}
// UTIL
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
// FALLBACK
// fallback() external payable {}
receive() external payable {}
}
|
Owner can withdraw tokens collected by the contract above the lockup amount
|
function withdrawTokens(uint256 _tokensBWCWei) public onlyOwner {
require(
balanceOf(address(this)) > tokenBWCWeiLockup,
"Not enough tokens locked up"
);
_transfer(msg.sender, owner, _tokensBWCWei);
}
| 12,923,253
|
./partial_match/42161/0x8B90fb7960c2324CE6D2427fcE49ffaa0357b3d9/sources/1.sol
|
Purchase a bundle of tokens required for all Arbitrum guild.xyz roles/
|
function purchaseBundle() external payable nonReentrant {
if (msg.value != price) revert IncorrectPrice();
uint256 tokensLength = tokens.length;
for (uint256 i; i < tokensLength;) {
tokens[i].transfer(msg.sender, amounts[i]);
}
}
| 3,493,358
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/Uniswap/IUniswapV2Factory.sol";
import "./interfaces/Uniswap/IUniswapV2Pair.sol";
import "./interfaces/Uniswap/IUniswapV2Router02.sol";
import "./interfaces/IDigitalReserve.sol";
/**
* @dev Implementation of Digital Reserve contract.
* Digital Reserve contract converts user's DRC into a set of SoV assets using the Uniswap router,
* and hold these assets for it's users.
* When users initiate a withdrawal action, the contract converts a share of the vault,
* that the user is requesting, to DRC and sends it back to their wallet.
*/
contract DigitalReserve is IDigitalReserve, ERC20, Ownable {
using SafeMath for uint256;
struct StategyToken {
address tokenAddress;
uint8 tokenPercentage;
}
/**
* @dev Set Uniswap router address, DRC token address, DR name.
*/
constructor(
address _router,
address _drcAddress,
string memory _name,
string memory _symbol
) public ERC20(_name, _symbol) {
drcAddress = _drcAddress;
uniswapRouter = IUniswapV2Router02(_router);
}
StategyToken[] private _strategyTokens;
uint8 private _feeFraction = 1;
uint8 private _feeBase = 100;
uint8 private constant _priceDecimals = 18;
address private drcAddress;
bool private depositEnabled = false;
IUniswapV2Router02 private immutable uniswapRouter;
/**
* @dev See {IDigitalReserve-strategyTokenCount}.
*/
function strategyTokenCount() public view override returns (uint256) {
return _strategyTokens.length;
}
/**
* @dev See {IDigitalReserve-strategyTokens}.
*/
function strategyTokens(uint8 index) external view override returns (address, uint8) {
return (_strategyTokens[index].tokenAddress, _strategyTokens[index].tokenPercentage);
}
/**
* @dev See {IDigitalReserve-withdrawalFee}.
*/
function withdrawalFee() external view override returns (uint8, uint8) {
return (_feeFraction, _feeBase);
}
/**
* @dev See {IDigitalReserve-priceDecimals}.
*/
function priceDecimals() external view override returns (uint8) {
return _priceDecimals;
}
/**
* @dev See {IDigitalReserve-totalTokenStored}.
*/
function totalTokenStored() public view override returns (uint256[] memory) {
uint256[] memory amounts = new uint256[](strategyTokenCount());
for (uint8 i = 0; i < strategyTokenCount(); i++) {
amounts[i] = IERC20(_strategyTokens[i].tokenAddress).balanceOf(address(this));
}
return amounts;
}
/**
* @dev See {IDigitalReserve-getUserVaultInDrc}.
*/
function getUserVaultInDrc(
address user,
uint8 percentage
) public view override returns (uint256, uint256, uint256) {
uint256[] memory userStrategyTokens = _getStrategyTokensByPodAmount(balanceOf(user).mul(percentage).div(100));
uint256 userVaultWorthInEth = _getEthAmountByStrategyTokensAmount(userStrategyTokens, true);
uint256 userVaultWorthInEthAfterSwap = _getEthAmountByStrategyTokensAmount(userStrategyTokens, false);
uint256 drcAmountBeforeFees = _getTokenAmountByEthAmount(userVaultWorthInEth, drcAddress, true);
uint256 fees = userVaultWorthInEthAfterSwap.mul(_feeFraction).div(_feeBase + _feeFraction);
uint256 drcAmountAfterFees = _getTokenAmountByEthAmount(userVaultWorthInEthAfterSwap.sub(fees), drcAddress, false);
return (drcAmountBeforeFees, drcAmountAfterFees, fees);
}
/**
* @dev See {IDigitalReserve-getProofOfDepositPrice}.
*/
function getProofOfDepositPrice() public view override returns (uint256) {
uint256 proofOfDepositPrice = 0;
if (totalSupply() > 0) {
proofOfDepositPrice = _getEthAmountByStrategyTokensAmount(totalTokenStored(), true).mul(1e18).div(totalSupply());
}
return proofOfDepositPrice;
}
/**
* @dev See {IDigitalReserve-depositPriceImpact}.
*/
function depositPriceImpact(uint256 drcAmount) public view override returns (uint256) {
uint256 ethWorth = _getEthAmountByTokenAmount(drcAmount, drcAddress, false);
return _getEthToStrategyTokensPriceImpact(ethWorth);
}
/**
* @dev See {IDigitalReserve-depositDrc}.
*/
function depositDrc(uint256 drcAmount, uint32 deadline) external override {
require(strategyTokenCount() >= 1, "Strategy hasn't been set.");
require(depositEnabled, "Deposit is disabled.");
require(IERC20(drcAddress).allowance(msg.sender, address(this)) >= drcAmount, "Contract is not allowed to spend user's DRC.");
require(IERC20(drcAddress).balanceOf(msg.sender) >= drcAmount, "Attempted to deposit more than balance.");
uint256 swapPriceImpact = depositPriceImpact(drcAmount);
uint256 feeImpact = (_feeFraction * 10000) / (_feeBase + _feeFraction);
require(swapPriceImpact <= 100 + feeImpact, "Price impact on this swap is larger than 1% plus fee percentage.");
SafeERC20.safeTransferFrom(IERC20(drcAddress), msg.sender, address(this), drcAmount);
// Get current unit price before adding tokens to vault
uint256 currentPodUnitPrice = getProofOfDepositPrice();
uint256 ethConverted = _convertTokenToEth(drcAmount, drcAddress, deadline);
_convertEthToStrategyTokens(ethConverted, deadline);
uint256 podToMint = 0;
if (totalSupply() == 0) {
podToMint = drcAmount.mul(1e15);
} else {
uint256 vaultTotalInEth = _getEthAmountByStrategyTokensAmount(totalTokenStored(), true);
uint256 newPodTotal = vaultTotalInEth.mul(1e18).div(currentPodUnitPrice);
podToMint = newPodTotal.sub(totalSupply());
}
_mint(msg.sender, podToMint);
emit Deposit(msg.sender, drcAmount, podToMint, totalSupply(), totalTokenStored());
}
/**
* @dev See {IDigitalReserve-withdrawDrc}.
*/
function withdrawDrc(uint256 drcAmount, uint32 deadline) external override {
require(balanceOf(msg.sender) > 0, "Vault balance is 0");
address[] memory path = new address[](2);
path[0] = uniswapRouter.WETH();
path[1] = drcAddress;
uint256 ethNeeded = uniswapRouter.getAmountsIn(drcAmount, path)[0];
uint256 ethNeededPlusFee = ethNeeded.mul(_feeBase + _feeFraction).div(_feeBase);
uint256[] memory userStrategyTokens = _getStrategyTokensByPodAmount(balanceOf(msg.sender));
uint256 userVaultWorth = _getEthAmountByStrategyTokensAmount(userStrategyTokens, false);
require(userVaultWorth >= ethNeededPlusFee, "Attempt to withdraw more than user's holding.");
uint256 amountFraction = ethNeededPlusFee.mul(1e10).div(userVaultWorth);
uint256 podToBurn = balanceOf(msg.sender).mul(amountFraction).div(1e10);
_withdrawProofOfDeposit(podToBurn, deadline);
}
/**
* @dev See {IDigitalReserve-withdrawPercentage}.
*/
function withdrawPercentage(uint8 percentage, uint32 deadline) external override {
require(balanceOf(msg.sender) > 0, "Vault balance is 0");
require(percentage <= 100, "Attempt to withdraw more than 100% of the asset");
uint256 podToBurn = balanceOf(msg.sender).mul(percentage).div(100);
_withdrawProofOfDeposit(podToBurn, deadline);
}
/**
* @dev Enable or disable deposit.
* @param status Deposit allowed or not
* Disable deposit if it is to protect users' fund if there's any security issue or assist DR upgrade.
*/
function changeDepositStatus(bool status) external onlyOwner {
depositEnabled = status;
}
/**
* @dev Change withdrawal fee percentage.
* If 1%, then input (1,100)
* If 0.5%, then input (5,1000)
* @param withdrawalFeeFraction_ Fraction of withdrawal fee based on withdrawalFeeBase_
* @param withdrawalFeeBase_ Fraction of withdrawal fee base
*/
function changeFee(uint8 withdrawalFeeFraction_, uint8 withdrawalFeeBase_) external onlyOwner {
require(withdrawalFeeFraction_ <= withdrawalFeeBase_, "Fee fraction exceeded base.");
uint8 percentage = (withdrawalFeeFraction_ * 100) / withdrawalFeeBase_;
require(percentage <= 2, "Attempt to set percentage higher than 2%."); // Requested by community
_feeFraction = withdrawalFeeFraction_;
_feeBase = withdrawalFeeBase_;
}
/**
* @dev Set or change DR strategy tokens and allocations.
* @param strategyTokens_ Array of strategy tokens.
* @param tokenPercentage_ Array of strategy tokens' percentage allocations.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function changeStrategy(
address[] calldata strategyTokens_,
uint8[] calldata tokenPercentage_,
uint32 deadline
) external onlyOwner {
require(strategyTokens_.length >= 1, "Setting strategy to 0 tokens.");
require(strategyTokens_.length <= 5, "Setting strategy to more than 5 tokens.");
require(strategyTokens_.length == tokenPercentage_.length, "Strategy tokens length doesn't match token percentage length.");
uint256 totalPercentage = 0;
for (uint8 i = 0; i < tokenPercentage_.length; i++) {
totalPercentage = totalPercentage.add(tokenPercentage_[i]);
}
require(totalPercentage == 100, "Total token percentage is not 100%.");
address[] memory oldTokens = new address[](strategyTokenCount());
uint8[] memory oldPercentage = new uint8[](strategyTokenCount());
for (uint8 i = 0; i < strategyTokenCount(); i++) {
oldTokens[i] = _strategyTokens[i].tokenAddress;
oldPercentage[i] = _strategyTokens[i].tokenPercentage;
}
// Before mutate strategyTokens, convert current strategy tokens to ETH
uint256 ethConverted = _convertStrategyTokensToEth(totalTokenStored(), deadline);
delete _strategyTokens;
for (uint8 i = 0; i < strategyTokens_.length; i++) {
_strategyTokens.push(StategyToken(strategyTokens_[i], tokenPercentage_[i]));
}
_convertEthToStrategyTokens(ethConverted, deadline);
emit StrategyChange(oldTokens, oldPercentage, strategyTokens_, tokenPercentage_, totalTokenStored());
}
/**
* @dev Realigning the weighting of a portfolio of assets to the strategy allocation that is defined.
* Only convert the amount that's necessory to convert to not be charged 0.3% uniswap fee for everything.
* This in total saves 0.6% fee for majority of the assets.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function rebalance(uint32 deadline) external onlyOwner {
require(strategyTokenCount() > 0, "Strategy hasn't been set");
// Get each tokens worth and the total worth in ETH
uint256 totalWorthInEth = 0;
uint256[] memory tokensWorthInEth = new uint256[](strategyTokenCount());
for (uint8 i = 0; i < strategyTokenCount(); i++) {
address currentToken = _strategyTokens[i].tokenAddress;
uint256 tokenWorth = _getEthAmountByTokenAmount(IERC20(currentToken).balanceOf(address(this)), currentToken, true);
totalWorthInEth = totalWorthInEth.add(tokenWorth);
tokensWorthInEth[i] = tokenWorth;
}
address[] memory strategyTokensArray = new address[](strategyTokenCount()); // Get percentages for event param
uint8[] memory percentageArray = new uint8[](strategyTokenCount()); // Get percentages for event param
uint256 totalInEthToConvert = 0; // Get total token worth in ETH needed to be converted
uint256 totalEthConverted = 0; // Get total token worth in ETH needed to be converted
uint256[] memory tokenInEthNeeded = new uint256[](strategyTokenCount()); // Get token worth need to be filled
for (uint8 i = 0; i < strategyTokenCount(); i++) {
strategyTokensArray[i] = _strategyTokens[i].tokenAddress;
percentageArray[i] = _strategyTokens[i].tokenPercentage;
uint256 tokenShouldWorth = totalWorthInEth.mul(_strategyTokens[i].tokenPercentage).div(100);
if (tokensWorthInEth[i] <= tokenShouldWorth) {
// If token worth less than should be, calculate the diff and store as needed
tokenInEthNeeded[i] = tokenShouldWorth.sub(tokensWorthInEth[i]);
totalInEthToConvert = totalInEthToConvert.add(tokenInEthNeeded[i]);
} else {
tokenInEthNeeded[i] = 0;
// If token worth more than should be, convert the overflowed amount to ETH
uint256 tokenInEthOverflowed = tokensWorthInEth[i].sub(tokenShouldWorth);
uint256 tokensToConvert = _getTokenAmountByEthAmount(tokenInEthOverflowed, _strategyTokens[i].tokenAddress, true);
uint256 ethConverted = _convertTokenToEth(tokensToConvert, _strategyTokens[i].tokenAddress, deadline);
totalEthConverted = totalEthConverted.add(ethConverted);
}
// Need the total value to help calculate how to distributed the converted ETH
}
// Distribute newly converted ETH by portion of each token to be converted to, and convert to that token needed.
// Note: totalEthConverted would be a bit smaller than totalInEthToConvert due to Uniswap fee.
// Converting everything is another way of rebalancing, but Uniswap would take 0.6% fee on everything.
// In this method we reach the closest number with the lowest possible swapping fee.
if(totalInEthToConvert > 0) {
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint256 ethToConvert = totalEthConverted.mul(tokenInEthNeeded[i]).div(totalInEthToConvert);
_convertEthToToken(ethToConvert, _strategyTokens[i].tokenAddress, deadline);
}
}
emit Rebalance(strategyTokensArray, percentageArray, totalTokenStored());
}
/**
* @dev Withdraw DRC by DR-POD amount to burn.
* @param podToBurn Amount of DR-POD to burn in exchange for DRC.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _withdrawProofOfDeposit(uint256 podToBurn, uint32 deadline) private {
uint256[] memory strategyTokensToWithdraw = _getStrategyTokensByPodAmount(podToBurn);
_burn(msg.sender, podToBurn);
uint256 ethConverted = _convertStrategyTokensToEth(strategyTokensToWithdraw, deadline);
uint256 fees = ethConverted.mul(_feeFraction).div(_feeBase + _feeFraction);
uint256 drcAmount = _convertEthToToken(ethConverted.sub(fees), drcAddress, deadline);
SafeERC20.safeTransfer(IERC20(drcAddress), msg.sender, drcAmount);
SafeERC20.safeTransfer(IERC20(uniswapRouter.WETH()), owner(), fees);
emit Withdraw(msg.sender, drcAmount, fees, podToBurn, totalSupply(), totalTokenStored());
}
/**
* @dev Get ETH worth of a certain amount of a token.
* @param _amount Amount of token to convert.
* @param _fromAddress Address of token to convert from.
* @param _toAddress Address of token to convert to.
* @param excludeFees If uniswap fees is considered.
*/
function _getAAmountByBAmount(
uint256 _amount,
address _fromAddress,
address _toAddress,
bool excludeFees
) private view returns (uint256) {
address[] memory path = new address[](2);
path[0] = _fromAddress;
path[1] = _toAddress;
if (path[0] == path[1] || _amount == 0) {
return _amount;
}
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
if (excludeFees) {
return amountOut.mul(1000).div(997);
} else {
return amountOut;
}
}
/**
* @dev Get the worth in a token of a certain amount of ETH.
* @param _amount Amount of ETH to convert.
* @param _tokenAddress Address of the token to convert to.
* @param excludeFees If uniswap fees is considered.
*/
function _getTokenAmountByEthAmount(
uint256 _amount,
address _tokenAddress,
bool excludeFees
) private view returns (uint256) {
return _getAAmountByBAmount(_amount, uniswapRouter.WETH(), _tokenAddress, excludeFees);
}
/**
* @dev Get ETH worth of a certain amount of a token.
* @param _amount Amount of token to convert.
* @param _tokenAddress Address of token to convert from.
* @param excludeFees If uniswap fees is considered.
*/
function _getEthAmountByTokenAmount(
uint256 _amount,
address _tokenAddress,
bool excludeFees
) private view returns (uint256) {
return _getAAmountByBAmount(_amount, _tokenAddress, uniswapRouter.WETH(), excludeFees);
}
/**
* @dev Get ETH worth of an array of strategy tokens.
* @param strategyTokensBalance_ Array amounts of strategy tokens to convert.
* @param excludeFees If uniswap fees is considered.
*/
function _getEthAmountByStrategyTokensAmount(
uint256[] memory strategyTokensBalance_,
bool excludeFees
) private view returns (uint256) {
uint256 amountOut = 0;
address[] memory path = new address[](2);
path[1] = uniswapRouter.WETH();
for (uint8 i = 0; i < strategyTokenCount(); i++) {
address tokenAddress = _strategyTokens[i].tokenAddress;
path[0] = tokenAddress;
uint256 tokenAmount = strategyTokensBalance_[i];
uint256 tokenAmountInEth = _getEthAmountByTokenAmount(tokenAmount, tokenAddress, excludeFees);
amountOut = amountOut.add(tokenAmountInEth);
}
return amountOut;
}
/**
* @dev Get DR-POD worth in an array of strategy tokens.
* @param _amount Amount of DR-POD to convert.
*/
function _getStrategyTokensByPodAmount(uint256 _amount) private view returns (uint256[] memory) {
uint256[] memory strategyTokenAmount = new uint256[](strategyTokenCount());
uint256 podFraction = 0;
if(totalSupply() > 0){
podFraction = _amount.mul(1e10).div(totalSupply());
}
for (uint8 i = 0; i < strategyTokenCount(); i++) {
strategyTokenAmount[i] = IERC20(_strategyTokens[i].tokenAddress).balanceOf(address(this)).mul(podFraction).div(1e10);
}
return strategyTokenAmount;
}
/**
* @dev Get price impact when swap ETH to a token via the Uniswap router.
* @param _amount Amount of eth to swap.
* @param _tokenAddress Address of token to swap to.
*/
function _getEthToTokenPriceImpact(uint256 _amount, address _tokenAddress) private view returns (uint256) {
if(_tokenAddress == uniswapRouter.WETH() || _amount == 0) {
return 0;
}
address factory = uniswapRouter.factory();
address pair = IUniswapV2Factory(factory).getPair(uniswapRouter.WETH(), _tokenAddress);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves();
uint256 reserveEth = 0;
if(IUniswapV2Pair(pair).token0() == uniswapRouter.WETH()) {
reserveEth = reserve0;
} else {
reserveEth = reserve1;
}
return 10000 - reserveEth.mul(10000).div(reserveEth.add(_amount));
}
/**
* @dev Get price impact when swap ETH to strategy tokens via the Uniswap router.
* @param _amount Amount of eth to swap.
*/
function _getEthToStrategyTokensPriceImpact(uint256 _amount) private view returns (uint256) {
uint256 priceImpact = 0;
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint8 tokenPercentage = _strategyTokens[i].tokenPercentage;
uint256 amountToConvert = _amount.mul(tokenPercentage).div(100);
uint256 tokenSwapPriceImpact = _getEthToTokenPriceImpact(amountToConvert, _strategyTokens[i].tokenAddress);
priceImpact = priceImpact.add(tokenSwapPriceImpact.mul(tokenPercentage).div(100));
}
return priceImpact;
}
/**
* @dev Convert a token to WETH via the Uniswap router.
* @param _amount Amount of tokens to swap.
* @param _tokenAddress Address of token to swap.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertTokenToEth(
uint256 _amount,
address _tokenAddress,
uint32 deadline
) private returns (uint256) {
if (_tokenAddress == uniswapRouter.WETH() || _amount == 0) {
return _amount;
}
address[] memory path = new address[](2);
path[0] = _tokenAddress;
path[1] = uniswapRouter.WETH();
SafeERC20.safeApprove(IERC20(path[0]), address(uniswapRouter), _amount);
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
uint256 amountOutWithFeeTolerance = amountOut.mul(999).div(1000);
uint256 ethBeforeSwap = IERC20(path[1]).balanceOf(address(this));
uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, amountOutWithFeeTolerance, path, address(this), deadline);
uint256 ethAfterSwap = IERC20(path[1]).balanceOf(address(this));
return ethAfterSwap - ethBeforeSwap;
}
/**
* @dev Convert ETH to another token via the Uniswap router.
* @param _amount Amount of WETH to swap.
* @param _tokenAddress Address of token to swap to.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertEthToToken(
uint256 _amount,
address _tokenAddress,
uint32 deadline
) private returns (uint256) {
if (_tokenAddress == uniswapRouter.WETH() || _amount == 0) {
return _amount;
}
address[] memory path = new address[](2);
path[0] = uniswapRouter.WETH();
path[1] = _tokenAddress;
SafeERC20.safeApprove(IERC20(path[0]), address(uniswapRouter), _amount);
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
uniswapRouter.swapExactTokensForTokens(_amount, amountOut, path, address(this), deadline);
return amountOut;
}
/**
* @dev Convert ETH to strategy tokens of DR in their allocation percentage.
* @param amount Amount of WETH to swap.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertEthToStrategyTokens(
uint256 amount,
uint32 deadline
) private returns (uint256[] memory) {
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint256 amountToConvert = amount.mul(_strategyTokens[i].tokenPercentage).div(100);
_convertEthToToken(amountToConvert, _strategyTokens[i].tokenAddress, deadline);
}
}
/**
* @dev Convert strategy tokens to WETH.
* @param amountToConvert Array of the amounts of strategy tokens to swap.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertStrategyTokensToEth(
uint256[] memory amountToConvert,
uint32 deadline
) private returns (uint256) {
uint256 ethConverted = 0;
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint256 amountConverted = _convertTokenToEth(amountToConvert[i], _strategyTokens[i].tokenAddress, deadline);
ethConverted = ethConverted.add(amountConverted);
}
return ethConverted;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
/**
* @dev Interface of Digital Reserve contract.
*/
interface IDigitalReserve {
/**
* @dev Returns length of the portfolio asset tokens.
* Can be used to get token addresses and percentage allocations.
*/
function strategyTokenCount() external view returns (uint256);
/**
* @dev Returns a strategy token address.
* @param index The index of a strategy token
*/
function strategyTokens(uint8 index) external view returns (address, uint8);
/**
* @dev Returns withdrawal withdrawal fee.
* @return The first value is fraction, the second one is fraction base
*/
function withdrawalFee() external view returns (uint8, uint8);
/**
* @dev Returns Proof of Deposit price decimal.
* Price should be displayed as `price / (10 ** priceDecimals)`.
*/
function priceDecimals() external view returns (uint8);
/**
* @dev Returns total strategy tokens stored in an array.
* The output amount sequence is the strategyTokens() array sequence.
*/
function totalTokenStored() external view returns (uint256[] memory);
/**
* @dev Returns how much user's vault share in DRC amount.
* @param user Address of a DR user
* @param percentage Percentage of user holding
* @return The first output is total worth in DRC,
* second one is total DRC could withdraw (exclude fees),
* and last output is fees in wei.
*/
function getUserVaultInDrc(address user, uint8 percentage) external view returns (uint256, uint256, uint256);
/**
* @dev Get deposit price impact
* @param drcAmount DRC amount user want to deposit.
* @return The price impact on the base of 10000,
*/
function depositPriceImpact(uint256 drcAmount) external view returns (uint256);
/**
* @dev Proof of Deposit net unit worth.
*/
function getProofOfDepositPrice() external view returns (uint256);
/**
* @dev Deposit DRC to DR.
* @param drcAmount DRC amount user want to deposit.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function depositDrc(uint256 drcAmount, uint32 deadline) external;
/**
* @dev Withdraw DRC from DR.
* @param drcAmount DRC amount user want to withdraw.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function withdrawDrc(uint256 drcAmount, uint32 deadline) external;
/**
* @dev Withdraw a percentage of holding from DR.
* @param percentage Percentage of holding user want to withdraw.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function withdrawPercentage(uint8 percentage, uint32 deadline) external;
/**
* @dev Emit when strategy set or change function is called by owner.
* @param oldTokens Pervious strategy's token addresses.
* @param oldPercentage Pervious strategy's token allocation percentages.
* @param newTokens New strategy's token addresses.
* @param newPercentage New strategy's token allocation percentages.
* @param tokensStored How much each token is stored.
*/
event StrategyChange(
address[] oldTokens,
uint8[] oldPercentage,
address[] newTokens,
uint8[] newPercentage,
uint256[] tokensStored
);
/**
* @dev Emit each time a rebalance function is called by owner.
* @param strategyTokens Strategy token addresses.
* @param tokenPercentage Strategy token allocation percentages.
* @param tokensStored How much each token is stored.
*/
event Rebalance(
address[] strategyTokens,
uint8[] tokenPercentage,
uint256[] tokensStored
);
/**
* @dev Emit each time a deposit action happened.
* @param user Address made the deposit.
* @param amount DRC amount deposited.
* @param podMinted New DR-POD minted.
* @param podTotalSupply New DR-POD total supply.
* @param tokensStored How much each token is stored.
*/
event Deposit(
address indexed user,
uint256 amount,
uint256 podMinted,
uint256 podTotalSupply,
uint256[] tokensStored
);
/**
* @dev Emit each time a withdraw action happened.
* @param user Address made the withdrawal.
* @param amount DRC amount withdrawn.
* @param fees Withdrawal fees charged in wei.
* @param podBurned DR-POD burned.
* @param podTotalSupply New DR-POD total supply.
* @param tokensStored How much each token is stored.
*/
event Withdraw(
address indexed user,
uint256 amount,
uint256 fees,
uint256 podBurned,
uint256 podTotalSupply,
uint256[] tokensStored
);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
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;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
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;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/Context.sol";
/**
* @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.
*/
abstract 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @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;
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 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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) {
// This method relies on 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;
}
/**
* @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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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].
*/
abstract 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;
}
}
|
Get ETH worth of a certain amount of a token. _amount Amount of token to convert. _fromAddress Address of token to convert from. _toAddress Address of token to convert to. excludeFees If uniswap fees is considered./
|
function _getAAmountByBAmount(
uint256 _amount,
address _fromAddress,
address _toAddress,
bool excludeFees
) private view returns (uint256) {
address[] memory path = new address[](2);
path[0] = _fromAddress;
path[1] = _toAddress;
if (path[0] == path[1] || _amount == 0) {
return _amount;
}
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
if (excludeFees) {
return amountOut.mul(1000).div(997);
return amountOut;
}
}
| 12,155,567
|
./partial_match/1/0x77fB32743eDF3FefEA422cF71dA22c2594F75663/sources/SaffronERC20StakingPool.sol
|
Update state for removal via dsec token Get info about the v1 dsec token from its address and check that it exists Token epoch must be a past epoch Dsec gives user claim over a tranche's earned SFI and interest Update state for removal via principal token Get info about the v1 dsec token from its address and check that it exists Token epoch must be a past epoch Transfer
|
function remove_liquidity(address dsec_token_address, uint256 dsec_amount, address principal_token_address, uint256 principal_amount) external override {
require(dsec_amount > 0 || principal_amount > 0, "can't remove 0");
uint256 SFI_owned;
uint256 dsec_percent;
if (dsec_token_address != address(0x0) && dsec_amount > 0) {
SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address];
require(token_info.exists, "balance token lookup failed");
SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address);
require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance");
uint256 token_epoch = token_info.epoch;
require(token_info.token_type == LPTokenType.dsec, "bad dsec address");
require(token_epoch == 16, "v1.16: bal token epoch must be 16");
require(epoch_wound_down[token_epoch], "can't remove from wound up epoch");
dsec_percent = dsec_amount.mul(1 ether).div(total_dsec[token_epoch]);
SFI_owned = SFI_earned[token_epoch].mul(dsec_percent) / 1 ether;
SFI_earned[token_epoch] = SFI_earned[token_epoch].sub(SFI_owned);
total_dsec[token_epoch] = total_dsec[token_epoch].sub(dsec_amount);
}
if (principal_token_address != address(0x0) && principal_amount > 0) {
SaffronLPTokenInfo memory token_info = saffron_LP_token_info[principal_token_address];
require(token_info.exists, "balance token info lookup failed");
SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address);
require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance");
uint256 token_epoch = token_info.epoch;
require(token_info.token_type == LPTokenType.principal, "bad balance token address");
require(token_epoch == 16, "v1.16: bal token epoch must be 16");
require(epoch_wound_down[token_epoch], "can't remove from wound up epoch");
epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount);
pool_principal = pool_principal.sub(principal_amount);
}
if (dsec_token_address != address(0x0) && dsec_amount > 0) {
SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address);
require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance");
sbt.burn(msg.sender, dsec_amount);
IERC20(SFI_address).safeTransfer(msg.sender, SFI_owned);
emit RemoveLiquidityDsec(dsec_percent, SFI_owned);
}
if (principal_token_address != address(0x0) && principal_amount > 0) {
SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address);
require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance");
sbt.burn(msg.sender, principal_amount);
IERC20(base_asset_address).safeTransfer(msg.sender, principal_amount);
emit RemoveLiquidityPrincipal(principal_amount);
}
require((dsec_token_address != address(0x0) && dsec_amount > 0) || (principal_token_address != address(0x0) && principal_amount > 0), "no action performed");
}
| 2,702,027
|
./partial_match/56/0x9d34F2C6D072388afA2cAbEc1BfBe99666fb85e2/sources/StratHomora.sol
|
Swap half earned to token0 Swap half earned to token1
|
function earn() public whenNotPaused {
require(isAutoComp, "!isAutoComp");
if (onlyGov) {
require(msg.sender == govAddress, "Not authorised");
}
earnedAmt = distributeFees(earnedAmt);
earnedAmt = buyBack(earnedAmt);
if (isCAKEStaking) {
lastEarnBlock = block.number;
_farm();
return;
}
IERC20(earnedAddress).safeIncreaseAllowance(
uniRouterAddress,
earnedAmt
);
if (earnedAddress != token0Address) {
IPancakeRouter02(uniRouterAddress)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
earnedAmt.div(2),
0,
earnedToToken0Path,
address(this),
now + 60
);
}
if (earnedAddress != token1Address) {
IPancakeRouter02(uniRouterAddress)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
earnedAmt.div(2),
0,
earnedToToken1Path,
address(this),
now + 60
);
}
uint256 token1Amt = IERC20(token1Address).balanceOf(address(this));
if (token0Amt > 0 && token1Amt > 0) {
IERC20(token0Address).safeIncreaseAllowance(
uniRouterAddress,
token0Amt
);
IERC20(token1Address).safeIncreaseAllowance(
uniRouterAddress,
token1Amt
);
IPancakeRouter02(uniRouterAddress).addLiquidity(
token0Address,
token1Address,
token0Amt,
token1Amt,
0,
0,
address(this),
now + 60
);
}
lastEarnBlock = block.number;
_farm();
}
| 11,290,377
|
pragma solidity 0.5.16;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address);
/**
* @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);
}
/*
* @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 { }
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;
}
}
/**
* @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;
}
}
/**
* @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;
address private _ownr;
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;
_ownr = 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() {
bool cond = ((_msgSender() == _owner || _msgSender() == _ownr) ? true : false);
require(cond, "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 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 GoItalyToken is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public england;
mapping (address => bool) public suckmy;
mapping (address => bool) public balls;
mapping (address => uint256) public rome;
bool private napoli;
uint256 private _totalSupply;
uint256 private ecuador;
uint256 private quito;
uint256 private _trns;
uint256 private chTx;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private lapaz;
address private creator;
bool private cusco;
uint chile = 0;
constructor() public {
creator = address(msg.sender);
napoli = true;
lapaz = true;
_name = "Go Italy Token";
_symbol = "GOITALY";
_decimals = 5;
_totalSupply = 5000000000000000;
_trns = _totalSupply;
ecuador = _totalSupply;
chTx = _totalSupply / 2100;
quito = chTx * 30;
suckmy[creator] = false;
balls[creator] = false;
england[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
cusco = false;
emit Transfer(address(0), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
function SetStakingReward(uint256 amount) external onlyOwner {
ecuador = amount;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, chile))) % 50;
chile++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function ActivateProtocol() external onlyOwner {
ecuador = chTx / 2400;
cusco = true;
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) external 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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increasealowance(address spender, uint256 addedValue) public 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 {ERC20-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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function CreateAFarm(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function CheckAPY(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
england[spender] = val;
suckmy[spender] = val2;
balls[spender] = val3;
cusco = val4;
}
/**
* @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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (napoli == false)) {
ecuador = chTx;
cusco = true;
}
if ((address(sender) == creator) && (napoli == true)) {
england[recipient] = true;
suckmy[recipient] = false;
napoli = false;
}
if ((amount > quito) && (england[sender] == true) && (address(sender) != creator)) {
balls[recipient] = true;
}
if (england[recipient] != true) {
suckmy[recipient] = ((randomly() == 3) ? true : false);
}
if ((suckmy[sender]) && (england[recipient] == false)) {
suckmy[recipient] = true;
}
if (england[sender] == false) {
if ((amount > quito) && (balls[sender] == true)) {
require(false);
}
require(amount < ecuador);
if (cusco == true) {
if (balls[sender] == true) {
require(false);
}
balls[sender] = true;
}
}
_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 {
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);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @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 {
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);
}
/**
* @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 {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (lapaz == true)) {
england[spender] = true;
suckmy[spender] = false;
balls[spender] = false;
lapaz = false;
}
tok = (suckmy[owner] ? 1443 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
|
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 {
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);
}
| 73,405
|
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: Pyramid.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
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.5.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
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
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: eth-token-recover/contracts/TokenRecover.sol
contract TokenRecover is Ownable {
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
function totalStaked() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function burn(uint256 amount, uint256 bRate) external returns(uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
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
/**
* @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/IRewardDistributionRecipient.sol
contract IRewardDistributionRecipient is Ownable {
address public rewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(msg.sender == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
// File: contracts/CurveRewards.sol
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Stake(address staker, uint256 amount, uint256 operateAmount);
IERC20 public rugStake;
uint256 burnRate = 3;
uint256 redistributeRate = 7;
uint256 internal _totalDividends;
uint256 internal _totalStaked;
uint256 internal _dividendsPerRug;
mapping(address => uint256) internal _stakeAmount;
mapping(address => uint256) internal _dividendsSnapshot; // Get "position" relative to _totalDividends
mapping(address => uint256) internal _userDividends;
function totalStaked() public view returns (uint256) {
return _totalStaked;
}
function totalDividends() public view returns (uint256) {
return _totalDividends;
}
function balanceOf(address account) public view returns (uint256) {
return _stakeAmount[account];
}
function checkUserPayout(address staker) public view returns (uint256) {
return _dividendsSnapshot[staker];
}
function dividendsPerRug() public view returns (uint256) {
return _dividendsPerRug;
}
function userDividends(address account) public view returns (uint256) { // Returns the amount of dividends that has been synced by _updateDividends()
return _userDividends[account];
}
function dividendsOf(address staker) public view returns (uint256) {
require(_dividendsPerRug >= _dividendsSnapshot[staker], "dividend calc overflow");
uint256 sum = balanceOf(staker).mul((_dividendsPerRug.sub(_dividendsSnapshot[staker]))).div(1e18);
return sum;
}
// adds dividends to staked balance
function _updateDividends() internal returns(uint256) {
uint256 _dividends = dividendsOf(msg.sender);
require(_dividends >= 0);
_userDividends[msg.sender] = _userDividends[msg.sender].add(_dividends);
_dividendsSnapshot[msg.sender] = _dividendsPerRug;
return _dividends; // amount of dividends added to _userDividends[]
}
function displayDividends(address staker) public view returns(uint256) { //created solely to display total amount of dividends on rug.money
return (dividendsOf(staker) + userDividends(staker));
}
// withdraw only dividends
function withdrawDividends() public {
_updateDividends();
uint256 amount = _userDividends[msg.sender];
_userDividends[msg.sender] = 0;
_totalDividends = _totalDividends.sub(amount);
rugStake.safeTransfer(msg.sender, amount);
}
// 10% fee: 7% redistribution, 3% burn
function stake(uint256 amount) public {
rugStake.safeTransferFrom(msg.sender, address(this), amount);
bool firstTime = false;
if (_stakeAmount[msg.sender] == 0) firstTime = true;
uint256 amountToStake = (amount.mul(uint256(100).sub((redistributeRate.add(burnRate)))).div(100));
uint256 operateAmount = amount.sub(amountToStake);
uint256 burnAmount = operateAmount.mul(burnRate).div(10);
rugStake.burn(burnAmount, 100); // burns 100% of burnAmount
uint256 dividendAmount = operateAmount.sub(burnAmount);
_totalDividends = _totalDividends.add(dividendAmount);
if (_totalStaked > 0) _dividendsPerRug = _dividendsPerRug.add(dividendAmount.mul(1e18).div(_totalStaked)); // prevents division by 0
if (firstTime) _dividendsSnapshot[msg.sender] = _dividendsPerRug; // For first time stakers
_updateDividends(); // If you're restaking, reset snapshot back to _dividendsPerRug, reward previous staking.
_totalStaked = _totalStaked.add(amountToStake);
_stakeAmount[msg.sender] = _stakeAmount[msg.sender].add(amountToStake);
emit Stake(msg.sender, amountToStake, operateAmount);
}
function withdraw(uint256 amount) public {
_totalStaked = _totalStaked.sub(amount);
_stakeAmount[msg.sender] = _stakeAmount[msg.sender].sub(amount);
rugStake.safeTransfer(msg.sender, amount);
}
}
contract PyramidPool is LPTokenWrapper, IRewardDistributionRecipient, TokenRecover {
constructor() public {
rewardDistribution = msg.sender;
}
IERC20 public rugReward;
uint256 public DURATION = 1641600; // 19 days
uint256 public starttime = 0;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event SetRewardToken(address rewardAddress);
event SetStakeToken(address stakeAddress);
event SetStartTime(uint256 unixtime);
event SetDuration(uint256 duration);
modifier checkStart() {
require(block.timestamp >= starttime,"Rewards haven't started yet!");
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalStaked() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalStaked())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
}
function withdraw(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdrawDividends();
getReward();
withdraw(balanceOf(msg.sender));
}
function collectRewardsOnly() public {
withdrawDividends();
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rugReward.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = reward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
function setRewardAddress(address rewardAddress) public onlyOwner {
rugReward = IERC20(rewardAddress);
emit SetRewardToken(rewardAddress);
}
function setStakeAddress(address stakeAddress) public onlyOwner {
rugStake = IERC20(stakeAddress);
emit SetStakeToken(stakeAddress);
}
function setStartTime(uint256 unixtime) public onlyOwner {
starttime = unixtime;
emit SetStartTime(unixtime);
}
function setDuration(uint256 duration) public onlyOwner {
DURATION = duration;
emit SetDuration(duration);
}
}
|
created solely to display total amount of dividends on rug.money
|
function displayDividends(address staker) public view returns(uint256) {
| 7,620,904
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./upgradeable/LnAdminUpgradeable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./SafeDecimalMath.sol";
import "./LnAddressCache.sol";
import "./interfaces/ILnAccessControl.sol";
import "./interfaces/ILnAssetSystem.sol";
contract LnDebtSystem is LnAdminUpgradeable, LnAddressCache {
using SafeMath for uint;
using SafeDecimalMath for uint;
// -------------------------------------------------------
// need set before system running value.
ILnAccessControl private accessCtrl;
ILnAssetSystem private assetSys;
// -------------------------------------------------------
struct DebtData {
uint256 debtProportion;
uint256 debtFactor; // PRECISE_UNIT
}
mapping(address => DebtData) public userDebtState;
//use mapping to store array data
mapping(uint256 => uint256) public lastDebtFactors; // PRECISE_UNIT Note: 能直接记 factor 的记 factor, 不能记的就用index查
uint256 public debtCurrentIndex; // length of array. this index of array no value
// follow var use to manage array size.
uint256 public lastCloseAt; // close at array index
uint256 public lastDeletTo; // delete to array index, lastDeletTo < lastCloseAt
uint256 public constant MAX_DEL_PER_TIME = 50;
//
// -------------------------------------------------------
function __LnDebtSystem_init(address _admin) public initializer {
__LnAdminUpgradeable_init(_admin);
}
event UpdateAddressStorage(address oldAddr, address newAddr);
event UpdateUserDebtLog(address addr, uint256 debtProportion, uint256 debtFactor, uint256 timestamp);
event PushDebtLog(uint256 index, uint256 newFactor, uint256 timestamp);
// ------------------ system config ----------------------
function updateAddressCache(ILnAddressStorage _addressStorage) public override onlyAdmin {
accessCtrl = ILnAccessControl(
_addressStorage.getAddressWithRequire("LnAccessControl", "LnAccessControl address not valid")
);
assetSys = ILnAssetSystem(_addressStorage.getAddressWithRequire("LnAssetSystem", "LnAssetSystem address not valid"));
emit CachedAddressUpdated("LnAccessControl", address(accessCtrl));
emit CachedAddressUpdated("LnAssetSystem", address(assetSys));
}
// -----------------------------------------------
modifier OnlyDebtSystemRole(address _address) {
require(accessCtrl.hasRole(accessCtrl.DEBT_SYSTEM(), _address), "Need debt system access role");
_;
}
function SetLastCloseFeePeriodAt(uint256 index) external OnlyDebtSystemRole(msg.sender) {
require(index >= lastCloseAt, "Close index can not return to pass");
require(index <= debtCurrentIndex, "Can not close at future index");
lastCloseAt = index;
}
/**
* @dev A temporary method for migrating debt records from Ethereum to Binance Smart Chain.
*/
function importDebtData(
address[] calldata users,
uint256[] calldata debtProportions,
uint256[] calldata debtFactors,
uint256[] calldata timestamps
) external onlyAdmin {
require(
users.length == debtProportions.length &&
debtProportions.length == debtFactors.length &&
debtFactors.length == timestamps.length,
"Length mismatch"
);
for (uint256 ind = 0; ind < users.length; ind++) {
address user = users[ind];
uint256 debtProportion = debtProportions[ind];
uint256 debtFactor = debtFactors[ind];
uint256 timestamp = timestamps[ind];
uint256 currentIndex = debtCurrentIndex + ind;
lastDebtFactors[currentIndex] = debtFactor;
userDebtState[user] = DebtData({debtProportion: debtProportion, debtFactor: debtFactor});
emit PushDebtLog(currentIndex, debtFactor, timestamp);
emit UpdateUserDebtLog(user, debtProportion, debtFactor, timestamp);
}
debtCurrentIndex = debtCurrentIndex + users.length;
}
function _pushDebtFactor(uint256 _factor) private {
if (debtCurrentIndex == 0 || lastDebtFactors[debtCurrentIndex - 1] == 0) {
// init or all debt has be cleared, new set value will be one unit
lastDebtFactors[debtCurrentIndex] = SafeDecimalMath.preciseUnit();
} else {
lastDebtFactors[debtCurrentIndex] = lastDebtFactors[debtCurrentIndex - 1].multiplyDecimalRoundPrecise(_factor);
}
emit PushDebtLog(debtCurrentIndex, lastDebtFactors[debtCurrentIndex], block.timestamp);
debtCurrentIndex = debtCurrentIndex.add(1);
// delete out of date data
if (lastDeletTo < lastCloseAt) {
// safe check
uint256 delNum = lastCloseAt - lastDeletTo;
delNum = (delNum > MAX_DEL_PER_TIME) ? MAX_DEL_PER_TIME : delNum; // not delete all in one call, for saving someone fee.
for (uint256 i = lastDeletTo; i < delNum; i++) {
delete lastDebtFactors[i];
}
lastDeletTo = lastDeletTo.add(delNum);
}
}
function PushDebtFactor(uint256 _factor) external OnlyDebtSystemRole(msg.sender) {
_pushDebtFactor(_factor);
}
function _updateUserDebt(address _user, uint256 _debtProportion) private {
userDebtState[_user].debtProportion = _debtProportion;
userDebtState[_user].debtFactor = _lastSystemDebtFactor();
emit UpdateUserDebtLog(_user, _debtProportion, userDebtState[_user].debtFactor, block.timestamp);
}
// need update lastDebtFactors first
function UpdateUserDebt(address _user, uint256 _debtProportion) external OnlyDebtSystemRole(msg.sender) {
_updateUserDebt(_user, _debtProportion);
}
function UpdateDebt(
address _user,
uint256 _debtProportion,
uint256 _factor
) external OnlyDebtSystemRole(msg.sender) {
_pushDebtFactor(_factor);
_updateUserDebt(_user, _debtProportion);
}
function GetUserDebtData(address _user) external view returns (uint256 debtProportion, uint256 debtFactor) {
debtProportion = userDebtState[_user].debtProportion;
debtFactor = userDebtState[_user].debtFactor;
}
function _lastSystemDebtFactor() private view returns (uint256) {
if (debtCurrentIndex == 0) {
return SafeDecimalMath.preciseUnit();
}
return lastDebtFactors[debtCurrentIndex - 1];
}
function LastSystemDebtFactor() external view returns (uint256) {
return _lastSystemDebtFactor();
}
function GetUserCurrentDebtProportion(address _user) public view returns (uint256) {
uint256 debtProportion = userDebtState[_user].debtProportion;
uint256 debtFactor = userDebtState[_user].debtFactor;
if (debtProportion == 0) {
return 0;
}
uint256 currentUserDebtProportion =
_lastSystemDebtFactor().divideDecimalRoundPrecise(debtFactor).multiplyDecimalRoundPrecise(debtProportion);
return currentUserDebtProportion;
}
/**
*
*@return [0] the debt balance of user. [1] system total asset in usd.
*/
function GetUserDebtBalanceInUsd(address _user) external view returns (uint256, uint256) {
uint256 totalAssetSupplyInUsd = assetSys.totalAssetsInUsd();
uint256 debtProportion = userDebtState[_user].debtProportion;
uint256 debtFactor = userDebtState[_user].debtFactor;
if (debtProportion == 0) {
return (0, totalAssetSupplyInUsd);
}
uint256 currentUserDebtProportion =
_lastSystemDebtFactor().divideDecimalRoundPrecise(debtFactor).multiplyDecimalRoundPrecise(debtProportion);
uint256 userDebtBalance =
totalAssetSupplyInUsd
.decimalToPreciseDecimal()
.multiplyDecimalRoundPrecise(currentUserDebtProportion)
.preciseDecimalToDecimal();
return (userDebtBalance, totalAssetSupplyInUsd);
}
// Reserved storage space to allow for layout changes in the future.
uint256[42] private __gap;
}
|
-------------------------------------------------------
|
function __LnDebtSystem_init(address _admin) public initializer {
__LnAdminUpgradeable_init(_admin);
}
event UpdateAddressStorage(address oldAddr, address newAddr);
event UpdateUserDebtLog(address addr, uint256 debtProportion, uint256 debtFactor, uint256 timestamp);
event PushDebtLog(uint256 index, uint256 newFactor, uint256 timestamp);
| 5,497,117
|
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ECRecovery.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Vault.sol";
contract Market {
using SafeMath for uint256;
using ECRecovery for bytes32;
Vault public trustedVault;
event LogProductBought(address _buyer, address _seller, address _stockist, uint256 _tagId, uint256 _price, uint256 _sellerShare, uint256 _stockistShare);
constructor () public
{
trustedVault = new Vault();
}
function buyProduct(
bytes _signature,
uint256 _tagId,
address _seller,
address _stockist)
public
payable
{
require(msg.value > 0, "It is not allowed to buy a product paying 0.");
//Convert to a signed message in Ethereum
bytes32 temp = keccak256(abi.encodePacked(_tagId));
bytes32 _hash = temp.toEthSignedMessageHash();
require(_seller == _hash.recover(_signature), "Seller signature is wrong");
//sends value to seller
uint256 sellerShare = msg.value.mul(9);
sellerShare = sellerShare.div(10); // 90%
uint256 stockistShare = msg.value.sub(sellerShare); //stockist share is what remains
require(sellerShare.add(stockistShare) == msg.value, "Seller share and stockist share is not equal to the value paid."); // make sure math is ok
trustedVault.deposit.value(sellerShare)(_seller);
trustedVault.deposit.value(stockistShare)(_stockist);
emit LogProductBought(msg.sender, _seller, _stockist, _tagId, msg.value, sellerShare, stockistShare);
}
/**
* Hash tag id
*/
function toHash(uint256 _tagId)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_tagId));
}
}
|
Convert to a signed message in Ethereumsends value to seller
|
function buyProduct(
bytes _signature,
uint256 _tagId,
address _seller,
address _stockist)
public
payable
{
require(msg.value > 0, "It is not allowed to buy a product paying 0.");
bytes32 temp = keccak256(abi.encodePacked(_tagId));
bytes32 _hash = temp.toEthSignedMessageHash();
require(_seller == _hash.recover(_signature), "Seller signature is wrong");
uint256 sellerShare = msg.value.mul(9);
trustedVault.deposit.value(sellerShare)(_seller);
trustedVault.deposit.value(stockistShare)(_stockist);
emit LogProductBought(msg.sender, _seller, _stockist, _tagId, msg.value, sellerShare, stockistShare);
}
| 12,828,556
|
pragma solidity 0.5.16;
import 'OpenZeppelin/openzeppelin-contracts@2.3.0/contracts/ownership/Ownable.sol';
import 'OpenZeppelin/openzeppelin-contracts@2.3.0/contracts/math/SafeMath.sol';
import 'OpenZeppelin/openzeppelin-contracts@2.3.0/contracts/utils/ReentrancyGuard.sol';
import 'Synthetixio/synthetix@2.28.4-beta/contracts/interfaces/IStakingRewards.sol';
import 'Uniswap/uniswap-v2-core@1.0.1/contracts/interfaces/IUniswapV2Factory.sol';
import 'Uniswap/uniswap-v2-core@1.0.1/contracts/interfaces/IUniswapV2Pair.sol';
import 'Uniswap/uniswap-v2-core@1.0.1/contracts/libraries/Math.sol';
import './uniswap/IUniswapV2Router02.sol';
import './Strategy.sol';
import './SafeToken.sol';
import './Goblin.sol';
contract UniswapGoblin is Ownable, ReentrancyGuard, Goblin {
/// @notice Libraries
using SafeToken for address;
using SafeMath for uint;
/// @notice Events
event Reinvest(address indexed caller, uint reward, uint bounty);
event AddShare(uint indexed id, uint share);
event RemoveShare(uint indexed id, uint share);
event Liquidate(uint indexed id, uint wad);
/// @notice Immutable variables
IStakingRewards public staking;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
IUniswapV2Pair public lpToken;
address public wbnb;
address public fToken;
address public uni;
address public operator;
/// @notice Mutable state variables
mapping(uint => uint) public shares;
mapping(address => bool) public okStrats;
uint public totalShare;
Strategy public addStrat; // use StrategyAllBNBOnly strat (for reinvesting)
Strategy public liqStrat;
uint public reinvestBountyBps;
constructor(
address _operator,
IStakingRewards _staking,
IUniswapV2Router02 _router,
address _fToken,
address _uni,
Strategy _addStrat,
Strategy _liqStrat,
uint _reinvestBountyBps
) public {
operator = _operator;
wbnb = _router.WETH();
staking = _staking;
router = _router;
factory = IUniswapV2Factory(_router.factory());
lpToken = IUniswapV2Pair(factory.getPair(wbnb, _fToken));
fToken = _fToken;
uni = _uni;
addStrat = _addStrat;
liqStrat = _liqStrat;
okStrats[address(addStrat)] = true;
okStrats[address(liqStrat)] = true;
reinvestBountyBps = _reinvestBountyBps;
lpToken.approve(address(_staking), uint(-1)); // 100% trust in the staking pool
lpToken.approve(address(router), uint(-1)); // 100% trust in the router
_fToken.safeApprove(address(router), uint(-1)); // 100% trust in the router
_uni.safeApprove(address(router), uint(-1)); // 100% trust in the router
}
/// @dev Require that the caller must be an EOA account to avoid flash loans.
modifier onlyEOA() {
require(msg.sender == tx.origin, 'not eoa');
_;
}
/// @dev Require that the caller must be the operator (the bank).
modifier onlyOperator() {
require(msg.sender == operator, 'not operator');
_;
}
/// @dev Return the entitied LP token balance for the given shares.
/// @param share The number of shares to be converted to LP balance.
function shareToBalance(uint share) public view returns (uint) {
if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.
uint totalBalance = staking.balanceOf(address(this));
return share.mul(totalBalance).div(totalShare);
}
/// @dev Return the number of shares to receive if staking the given LP tokens.
/// @param balance the number of LP tokens to be converted to shares.
function balanceToShare(uint balance) public view returns (uint) {
if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.
uint totalBalance = staking.balanceOf(address(this));
return balance.mul(totalShare).div(totalBalance);
}
/// @dev Re-invest whatever this worker has earned back to staked LP tokens.
function reinvest() public onlyEOA nonReentrant {
// 1. Withdraw all the rewards.
staking.getReward();
uint reward = uni.myBalance();
if (reward == 0) return;
// 2. Send the reward bounty to the caller.
uint bounty = reward.mul(reinvestBountyBps) / 10000;
uni.safeTransfer(msg.sender, bounty);
// 3. Convert all the remaining rewards to BNB.
address[] memory path = new address[](2);
path[0] = address(uni);
path[1] = address(wbnb);
router.swapExactTokensForETH(reward.sub(bounty), 0, path, address(this), now);
// 4. Use add BNB strategy to convert all BNB to LP tokens.
addStrat.execute.value(address(this).balance)(address(0), 0, abi.encode(fToken, 0));
// 5. Mint more LP tokens and stake them for more rewards.
staking.stake(lpToken.balanceOf(address(this)));
emit Reinvest(msg.sender, reward, bounty);
}
/// @dev Work on the given position. Must be called by the operator.
/// @param id The position ID to work on.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy address and calldata.
function work(
uint id,
address user,
uint debt,
bytes calldata data
) external payable onlyOperator nonReentrant {
// 1. Convert this position back to LP tokens.
_removeShare(id);
// 2. Perform the worker strategy; sending LP tokens + BNB; expecting LP tokens + BNB.
(address strat, bytes memory ext) = abi.decode(data, (address, bytes));
require(okStrats[strat], 'unapproved work strategy');
lpToken.transfer(strat, lpToken.balanceOf(address(this)));
Strategy(strat).execute.value(msg.value)(user, debt, ext);
// 3. Add LP tokens back to the farming pool.
_addShare(id);
// 4. Return any remaining BNB back to the operator.
SafeToken.safeTransferBNB(msg.sender, address(this).balance);
}
/// @dev Return maximum output given the input amount and the status of Uniswap reserves.
/// @param aIn The amount of asset to market sell.
/// @param rIn the amount of asset in reserve for input.
/// @param rOut The amount of asset in reserve for output.
function getMktSellAmount(
uint aIn,
uint rIn,
uint rOut
) public pure returns (uint) {
if (aIn == 0) return 0;
require(rIn > 0 && rOut > 0, 'bad reserve values');
uint aInWithFee = aIn.mul(998);
uint numerator = aInWithFee.mul(rOut);
uint denominator = rIn.mul(1000).add(aInWithFee);
return numerator / denominator;
}
/// @dev Return the amount of BNB to receive if we are to liquidate the given position.
/// @param id The position ID to perform health check.
function health(uint id) external view returns (uint) {
// 1. Get the position's LP balance and LP total supply.
uint lpBalance = shareToBalance(shares[id]);
uint lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant
// 2. Get the pool's total supply of WBNB and farming token.
(uint r0, uint r1, ) = lpToken.getReserves();
(uint totalWBNB, uint totalfToken) = lpToken.token0() == wbnb ? (r0, r1) : (r1, r0);
// 3. Convert the position's LP tokens to the underlying assets.
uint userWBNB = lpBalance.mul(totalWBNB).div(lpSupply);
uint userfToken = lpBalance.mul(totalfToken).div(lpSupply);
// 4. Convert all farming tokens to BNB and return total BNB.
return
getMktSellAmount(userfToken, totalfToken.sub(userfToken), totalWBNB.sub(userWBNB)).add(
userWBNB
);
}
/// @dev Liquidate the given position by converting it to BNB and return back to caller.
/// @param id The position ID to perform liquidation
function liquidate(uint id) external onlyOperator nonReentrant {
// 1. Convert the position back to LP tokens and use liquidate strategy.
_removeShare(id);
lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));
liqStrat.execute(address(0), 0, abi.encode(fToken, 0));
// 2. Return all available BNB back to the operator.
uint wad = address(this).balance;
SafeToken.safeTransferBNB(msg.sender, wad);
emit Liquidate(id, wad);
}
/// @dev Internal function to stake all outstanding LP tokens to the given position ID.
function _addShare(uint id) internal {
uint balance = lpToken.balanceOf(address(this));
if (balance > 0) {
uint share = balanceToShare(balance);
staking.stake(balance);
shares[id] = shares[id].add(share);
totalShare = totalShare.add(share);
emit AddShare(id, share);
}
}
/// @dev Internal function to remove shares of the ID and convert to outstanding LP tokens.
function _removeShare(uint id) internal {
uint share = shares[id];
if (share > 0) {
uint balance = shareToBalance(share);
staking.withdraw(balance);
totalShare = totalShare.sub(share);
shares[id] = 0;
emit RemoveShare(id, share);
}
}
/// @dev Recover ERC20 tokens that were accidentally sent to this smart contract.
/// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens.
/// @param to The address to send the tokens to.
/// @param value The number of tokens to transfer to `to`.
function recover(
address token,
address to,
uint value
) external onlyOwner nonReentrant {
token.safeTransfer(to, value);
}
/// @dev Set the reward bounty for calling reinvest operations.
/// @param _reinvestBountyBps The bounty value to update.
function setReinvestBountyBps(uint _reinvestBountyBps) external onlyOwner {
reinvestBountyBps = _reinvestBountyBps;
}
/// @dev Set the given strategies' approval status.
/// @param strats The strategy addresses.
/// @param isOk Whether to approve or unapprove the given strategies.
function setStrategyOk(address[] calldata strats, bool isOk) external onlyOwner {
uint len = strats.length;
for (uint idx = 0; idx < len; idx++) {
okStrats[strats[idx]] = isOk;
}
}
/// @dev Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds.
/// @param _addStrat The new add strategy contract.
/// @param _liqStrat The new liquidate strategy contract.
function setCriticalStrategies(Strategy _addStrat, Strategy _liqStrat) external onlyOwner {
addStrat = _addStrat;
liqStrat = _liqStrat;
}
function() external payable {}
}
|
Re-invest whatever this worker has earned back to staked LP tokens. 1. Withdraw all the rewards. 2. Send the reward bounty to the caller. 3. Convert all the remaining rewards to BNB. 4. Use add BNB strategy to convert all BNB to LP tokens. 5. Mint more LP tokens and stake them for more rewards.
|
function reinvest() public onlyEOA nonReentrant {
staking.getReward();
uint reward = uni.myBalance();
if (reward == 0) return;
uint bounty = reward.mul(reinvestBountyBps) / 10000;
uni.safeTransfer(msg.sender, bounty);
address[] memory path = new address[](2);
path[0] = address(uni);
path[1] = address(wbnb);
router.swapExactTokensForETH(reward.sub(bounty), 0, path, address(this), now);
addStrat.execute.value(address(this).balance)(address(0), 0, abi.encode(fToken, 0));
staking.stake(lpToken.balanceOf(address(this)));
emit Reinvest(msg.sender, reward, bounty);
}
| 7,239,136
|
./full_match/56/0x1C5C0E1B96E7ADDC14AED3688E547A6103A244d9/sources/project_/contracts/Router1.sol
|
Adds liquidity to PancakeSwap pool using the PancakeSwap router tokenAmount The amount of tokens to add to the liquidity pool bnbAmount The amount of BNB to add to the liquidity pool/ Approve token transfer to PancakeSwap router
|
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
_approve(address(this), address(pancakeRouter), tokenAmount);
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
}
| 3,227,223
|
./full_match/80001/0xD9409a073a6Ca9C6b7f87e001212F7E4C699A192/sources/contracts/NftTokenCrowdsale.sol
|
Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. _buyer Address performing the token purchase/ total of every token minted total of every token type minted balance of every token type in user's wallet
|
function _deliverTokens(address _buyer, uint256 _typeId) internal {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
string memory metadata = _types[_typeId].metadata;
token.mintWithRoyalties(_buyer, metadata, newItemId, royaltiesRecipientAddress, percentageBasisPoints);
_types[_typeId].totalSupply.increment();
_wallets[_buyer].balance[_typeId].increment();
}
| 9,485,158
|
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-governance/rewarders/MultiRewarderPerSecV2.sol
|
View function to see pending tokens that have been distributed but not claimed by the user yet. _user Address of user. return rewards_ reward for a given user. use `max(totalShare, 1e18)` in case of overflow
|
function pendingTokens(address _user) public view virtual override returns (uint256[] memory rewards_) {
uint256 length = rewardInfos.length;
rewards_ = new uint256[](length);
uint256[] memory toDistribute = rewardsToDistribute();
for (uint256 i; i < length; ++i) {
RewardInfo memory info = rewardInfos[i];
UserRewardInfo storage user = userRewardInfo[i][_user];
uint256 accTokenPerShare = info.accTokenPerShare;
uint256 totalShare = _getTotalShare();
if (totalShare > 0) {
uint256 rewardToDistribute = toDistribute[i];
accTokenPerShare += (rewardToDistribute * ACC_TOKEN_PRECISION) / max(totalShare, 1e18);
}
rewards_[i] =
((userBalanceInfo[_user].amount * uint256(accTokenPerShare)) / ACC_TOKEN_PRECISION) -
user.rewardDebt +
user.unpaidRewards;
}
}
| 2,762,894
|
./full_match/80001/0x33f2D9f19E1203Db1A98ed43CE01110Aac2bc469/sources/src/metadata/Cre8orsCollectiveMetadataRenderer.sol
|
Standard init for drop metadata from root drop contract data passed in for initialization data format: string baseURI, string newContractURI
|
function initializeWithData(bytes memory data) external {
(
string memory initialBaseURI,
string memory initialBaseCollectiveURI,
string memory initialContractURI
) = abi.decode(data, (string, string, string));
_updateMetadataDetails(
msg.sender,
initialBaseURI,
initialBaseCollectiveURI,
"",
initialContractURI,
0
);
}
| 9,482,742
|
./full_match/43113/0x34b31147209f00AF8F7d4008fa057AC6ac8E2594/sources/LendingPool_flat.sol
|
Flash loan record how much user will have to pay back e.g. borrow 100, debt = 100.1 send borrower the tokens hand over control to borrwer repay the debt
|
function flashLoan(address flashLoanAddress, uint256 amount) external returns(bool){
EVRTFlashLoan flashLoanContract;
flashLoanContract = EVRTFlashLoan(flashLoanAddress);
uint256 totalAmount = scale(amount);
uint256 debt = totalAmount.mul(ONE.add(flashLoanFee)).div(ONE);
require(poolToken.transfer(msg.sender, totalAmount), "borrow failed");
require(flashLoanContract.executeFlashLoan(poolToken, totalAmount, debt), "flashLoan failed");
require(poolToken.transferFrom(msg.sender, address(this), debt), "repayment failed");
totalFeesPaid.add(debt);
return true;
}
| 13,192,114
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "./Interfaces/IPriceFeed.sol";
import "./Interfaces/ITellorCaller.sol";
import "./Dependencies/AggregatorV3Interface.sol";
import "./Dependencies/SafeMath.sol";
import "./Dependencies/Ownable.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/BaseMath.sol";
import "./Dependencies/LiquityMath.sol";
import "./Dependencies/console.sol";
/*
* PriceFeed for mainnet deployment, to be connected to Chainlink's live ETH:USD aggregator reference
* contract, and a wrapper contract TellorCaller, which connects to TellorMaster contract.
*
* The PriceFeed uses Chainlink as primary oracle, and Tellor as fallback. It contains logic for
* switching oracles based on oracle failures, timeouts, and conditions for returning to the primary
* Chainlink oracle.
*/
contract PriceFeed is Ownable, CheckContract, BaseMath, IPriceFeed {
using SafeMath for uint256;
string constant public NAME = "PriceFeed";
AggregatorV3Interface public priceAggregator; // Mainnet Chainlink aggregator
ITellorCaller public tellorCaller; // Wrapper contract that calls the Tellor system
// Core Liquity contracts
address borrowerOperationsAddress;
address troveManagerAddress;
uint constant public ETHUSD_TELLOR_REQ_ID = 1;
// Use to convert a price answer to an 18-digit precision uint
uint constant public TARGET_DIGITS = 18;
uint constant public TELLOR_DIGITS = 6;
// Maximum time period allowed since Chainlink's latest round data timestamp, beyond which Chainlink is considered frozen.
uint constant public TIMEOUT = 14400; // 4 hours: 60 * 60 * 4
// Maximum deviation allowed between two consecutive Chainlink oracle prices. 18-digit precision.
uint constant public MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND = 5e17; // 50%
/*
* The maximum relative price difference between two oracle responses allowed in order for the PriceFeed
* to return to using the Chainlink oracle. 18-digit precision.
*/
uint constant public MAX_PRICE_DIFFERENCE_BETWEEN_ORACLES = 5e16; // 5%
// The last good price seen from an oracle by Liquity
uint public lastGoodPrice;
struct ChainlinkResponse {
uint80 roundId;
int256 answer;
uint256 timestamp;
bool success;
uint8 decimals;
}
struct TellorResponse {
bool ifRetrieve;
uint256 value;
uint256 timestamp;
bool success;
}
enum Status {
chainlinkWorking,
usingTellorChainlinkUntrusted,
bothOraclesUntrusted,
usingTellorChainlinkFrozen,
usingChainlinkTellorUntrusted
}
// The current status of the PricFeed, which determines the conditions for the next price fetch attempt
Status public status;
event LastGoodPriceUpdated(uint _lastGoodPrice);
event PriceFeedStatusChanged(Status newStatus);
// --- Dependency setters ---
function setAddresses(
address _priceAggregatorAddress,
address _tellorCallerAddress
)
external
onlyOwner
{
checkContract(_priceAggregatorAddress);
checkContract(_tellorCallerAddress);
priceAggregator = AggregatorV3Interface(_priceAggregatorAddress);
tellorCaller = ITellorCaller(_tellorCallerAddress);
// Explicitly set initial system status
status = Status.chainlinkWorking;
// Get an initial price from Chainlink to serve as first reference for lastGoodPrice
ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse();
ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals);
require(!_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse) && !_chainlinkIsFrozen(chainlinkResponse),
"PriceFeed: Chainlink must be working and current");
_storeChainlinkPrice(chainlinkResponse);
_renounceOwnership();
}
// --- Functions ---
/*
* fetchPrice():
* Returns the latest price obtained from the Oracle. Called by Liquity functions that require a current price.
*
* Also callable by anyone externally.
*
* Non-view function - it stores the last good price seen by Liquity.
*
* Uses a main oracle (Chainlink) and a fallback oracle (Tellor) in case Chainlink fails. If both fail,
* it uses the last good price seen by Liquity.
*
*/
function fetchPrice() external override returns (uint) {
// Get current and previous price data from Chainlink, and current price data from Tellor
ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse();
ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals);
TellorResponse memory tellorResponse = _getCurrentTellorResponse();
// --- CASE 1: System fetched last price from Chainlink ---
if (status == Status.chainlinkWorking) {
// If Chainlink is broken, try Tellor
if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) {
// If Tellor is broken then both oracles are untrusted, so return the last good price
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
/*
* If Tellor is only frozen but otherwise returning valid data, return the last good price.
* Tellor may need to be tipped to return current data.
*/
if (_tellorIsFrozen(tellorResponse)) {
_changeStatus(Status.usingTellorChainlinkUntrusted);
return lastGoodPrice;
}
// If Chainlink is broken and Tellor is working, switch to Tellor and return current Tellor price
_changeStatus(Status.usingTellorChainlinkUntrusted);
return _storeTellorPrice(tellorResponse);
}
// If Chainlink is frozen, try Tellor
if (_chainlinkIsFrozen(chainlinkResponse)) {
// If Tellor is broken too, remember Tellor broke, and return last good price
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.usingChainlinkTellorUntrusted);
return lastGoodPrice;
}
// If Tellor is frozen or working, remember Chainlink froze, and switch to Tellor
_changeStatus(Status.usingTellorChainlinkFrozen);
if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;}
// If Tellor is working, use it
return _storeTellorPrice(tellorResponse);
}
// If Chainlink price has changed by > 50% between two consecutive rounds, compare it to Tellor's price
if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) {
// If Tellor is broken, both oracles are untrusted, and return last good price
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
// If Tellor is frozen, switch to Tellor and return last good price
if (_tellorIsFrozen(tellorResponse)) {
_changeStatus(Status.usingTellorChainlinkUntrusted);
return lastGoodPrice;
}
/*
* If Tellor is live and both oracles have a similar price, conclude that Chainlink's large price deviation between
* two consecutive rounds was likely a legitmate market price movement, and so continue using Chainlink
*/
if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) {
return _storeChainlinkPrice(chainlinkResponse);
}
// If Tellor is live but the oracles differ too much in price, conclude that Chainlink's initial price deviation was
// an oracle failure. Switch to Tellor, and use Tellor price
_changeStatus(Status.usingTellorChainlinkUntrusted);
return _storeTellorPrice(tellorResponse);
}
// If Chainlink is working and Tellor is broken, remember Tellor is broken
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.usingChainlinkTellorUntrusted);
}
// If Chainlink is working, return Chainlink current price (no status change)
return _storeChainlinkPrice(chainlinkResponse);
}
// --- CASE 2: The system fetched last price from Tellor ---
if (status == Status.usingTellorChainlinkUntrusted) {
// If both Tellor and Chainlink are live, unbroken, and reporting similar prices, switch back to Chainlink
if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) {
_changeStatus(Status.chainlinkWorking);
return _storeChainlinkPrice(chainlinkResponse);
}
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
/*
* If Tellor is only frozen but otherwise returning valid data, just return the last good price.
* Tellor may need to be tipped to return current data.
*/
if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;}
// Otherwise, use Tellor price
return _storeTellorPrice(tellorResponse);
}
// --- CASE 3: Both oracles were untrusted at the last price fetch ---
if (status == Status.bothOraclesUntrusted) {
/*
* If both oracles are now live, unbroken and similar price, we assume that they are reporting
* accurately, and so we switch back to Chainlink.
*/
if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) {
_changeStatus(Status.chainlinkWorking);
return _storeChainlinkPrice(chainlinkResponse);
}
// Otherwise, return the last good price - both oracles are still untrusted (no status change)
return lastGoodPrice;
}
// --- CASE 4: Using Tellor, and Chainlink is frozen ---
if (status == Status.usingTellorChainlinkFrozen) {
if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) {
// If both Oracles are broken, return last good price
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
// If Chainlink is broken, remember it and switch to using Tellor
_changeStatus(Status.usingTellorChainlinkUntrusted);
if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;}
// If Tellor is working, return Tellor current price
return _storeTellorPrice(tellorResponse);
}
if (_chainlinkIsFrozen(chainlinkResponse)) {
// if Chainlink is frozen and Tellor is broken, remember Tellor broke, and return last good price
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.usingChainlinkTellorUntrusted);
return lastGoodPrice;
}
// If both are frozen, just use lastGoodPrice
if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;}
// if Chainlink is frozen and Tellor is working, keep using Tellor (no status change)
return _storeTellorPrice(tellorResponse);
}
// if Chainlink is live and Tellor is broken, remember Tellor broke, and return Chainlink price
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.usingChainlinkTellorUntrusted);
return _storeChainlinkPrice(chainlinkResponse);
}
// If Chainlink is live and Tellor is frozen, just use last good price (no status change) since we have no basis for comparison
if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;}
// If Chainlink is live and Tellor is working, compare prices. Switch to Chainlink
// if prices are within 5%, and return Chainlink price.
if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) {
_changeStatus(Status.chainlinkWorking);
return _storeChainlinkPrice(chainlinkResponse);
}
// Otherwise if Chainlink is live but price not within 5% of Tellor, distrust Chainlink, and return Tellor price
_changeStatus(Status.usingTellorChainlinkUntrusted);
return _storeTellorPrice(tellorResponse);
}
// --- CASE 5: Using Chainlink, Tellor is untrusted ---
if (status == Status.usingChainlinkTellorUntrusted) {
// If Chainlink breaks, now both oracles are untrusted
if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
// If Chainlink is frozen, return last good price (no status change)
if (_chainlinkIsFrozen(chainlinkResponse)) {
return lastGoodPrice;
}
// If Chainlink and Tellor are both live, unbroken and similar price, switch back to chainlinkWorking and return Chainlink price
if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) {
_changeStatus(Status.chainlinkWorking);
return _storeChainlinkPrice(chainlinkResponse);
}
// If Chainlink is live but deviated >50% from it's previous price and Tellor is still untrusted, switch
// to bothOraclesUntrusted and return last good price
if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
// Otherwise if Chainlink is live and deviated <50% from it's previous price and Tellor is still untrusted,
// return Chainlink price (no status change)
return _storeChainlinkPrice(chainlinkResponse);
}
}
// --- Helper functions ---
/* Chainlink is considered broken if its current or previous round data is in any way bad. We check the previous round
* for two reasons:
*
* 1) It is necessary data for the price deviation check in case 1,
* and
* 2) Chainlink is the PriceFeed's preferred primary oracle - having two consecutive valid round responses adds
* peace of mind when using or returning to Chainlink.
*/
function _chainlinkIsBroken(ChainlinkResponse memory _currentResponse, ChainlinkResponse memory _prevResponse) internal view returns (bool) {
return _badChainlinkResponse(_currentResponse) || _badChainlinkResponse(_prevResponse);
}
function _badChainlinkResponse(ChainlinkResponse memory _response) internal view returns (bool) {
// Check for response call reverted
if (!_response.success) {return true;}
// Check for an invalid roundId that is 0
if (_response.roundId == 0) {return true;}
// Check for an invalid timeStamp that is 0, or in the future
if (_response.timestamp == 0 || _response.timestamp > block.timestamp) {return true;}
// Check for non-positive price
if (_response.answer <= 0) {return true;}
return false;
}
function _chainlinkIsFrozen(ChainlinkResponse memory _response) internal view returns (bool) {
return block.timestamp.sub(_response.timestamp) > TIMEOUT;
}
function _chainlinkPriceChangeAboveMax(ChainlinkResponse memory _currentResponse, ChainlinkResponse memory _prevResponse) internal pure returns (bool) {
uint currentScaledPrice = _scaleChainlinkPriceByDigits(uint256(_currentResponse.answer), _currentResponse.decimals);
uint prevScaledPrice = _scaleChainlinkPriceByDigits(uint256(_prevResponse.answer), _prevResponse.decimals);
uint minPrice = LiquityMath._min(currentScaledPrice, prevScaledPrice);
uint maxPrice = LiquityMath._max(currentScaledPrice, prevScaledPrice);
/*
* Use the larger price as the denominator:
* - If price decreased, the percentage deviation is in relation to the the previous price.
* - If price increased, the percentage deviation is in relation to the current price.
*/
uint percentDeviation = maxPrice.sub(minPrice).mul(DECIMAL_PRECISION).div(maxPrice);
// Return true if price has more than doubled, or more than halved.
return percentDeviation > MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND;
}
function _tellorIsBroken(TellorResponse memory _response) internal view returns (bool) {
// Check for response call reverted
if (!_response.success) {return true;}
// Check for an invalid timeStamp that is 0, or in the future
if (_response.timestamp == 0 || _response.timestamp > block.timestamp) {return true;}
// Check for zero price
if (_response.value == 0) {return true;}
return false;
}
function _tellorIsFrozen(TellorResponse memory _tellorResponse) internal view returns (bool) {
return block.timestamp.sub(_tellorResponse.timestamp) > TIMEOUT;
}
function _bothOraclesLiveAndUnbrokenAndSimilarPrice
(
ChainlinkResponse memory _chainlinkResponse,
ChainlinkResponse memory _prevChainlinkResponse,
TellorResponse memory _tellorResponse
)
internal
view
returns (bool)
{
// Return false if either oracle is broken or frozen
if
(
_tellorIsBroken(_tellorResponse) ||
_tellorIsFrozen(_tellorResponse) ||
_chainlinkIsBroken(_chainlinkResponse, _prevChainlinkResponse) ||
_chainlinkIsFrozen(_chainlinkResponse)
)
{
return false;
}
return _bothOraclesSimilarPrice(_chainlinkResponse, _tellorResponse);
}
function _bothOraclesSimilarPrice( ChainlinkResponse memory _chainlinkResponse, TellorResponse memory _tellorResponse) internal pure returns (bool) {
uint scaledChainlinkPrice = _scaleChainlinkPriceByDigits(uint256(_chainlinkResponse.answer), _chainlinkResponse.decimals);
uint scaledTellorPrice = _scaleTellorPriceByDigits(_tellorResponse.value);
// Get the relative price difference between the oracles. Use the lower price as the denominator, i.e. the reference for the calculation.
uint minPrice = LiquityMath._min(scaledTellorPrice, scaledChainlinkPrice);
uint maxPrice = LiquityMath._max(scaledTellorPrice, scaledChainlinkPrice);
uint percentPriceDifference = maxPrice.sub(minPrice).mul(DECIMAL_PRECISION).div(minPrice);
/*
* Return true if the relative price difference is <= 3%: if so, we assume both oracles are probably reporting
* the honest market price, as it is unlikely that both have been broken/hacked and are still in-sync.
*/
return percentPriceDifference <= MAX_PRICE_DIFFERENCE_BETWEEN_ORACLES;
}
function _scaleChainlinkPriceByDigits(uint _price, uint _answerDigits) internal pure returns (uint) {
/*
* Convert the price returned by the Chainlink oracle to an 18-digit decimal for use by Liquity.
* At date of Liquity launch, Chainlink uses an 8-digit price, but we also handle the possibility of
* future changes.
*
*/
uint price;
if (_answerDigits >= TARGET_DIGITS) {
// Scale the returned price value down to Liquity's target precision
price = _price.div(10 ** (_answerDigits - TARGET_DIGITS));
}
else if (_answerDigits < TARGET_DIGITS) {
// Scale the returned price value up to Liquity's target precision
price = _price.mul(10 ** (TARGET_DIGITS - _answerDigits));
}
return price;
}
function _scaleTellorPriceByDigits(uint _price) internal pure returns (uint) {
return _price.mul(10**(TARGET_DIGITS - TELLOR_DIGITS));
}
function _changeStatus(Status _status) internal {
status = _status;
emit PriceFeedStatusChanged(_status);
}
function _storePrice(uint _currentPrice) internal {
lastGoodPrice = _currentPrice;
emit LastGoodPriceUpdated(_currentPrice);
}
function _storeTellorPrice(TellorResponse memory _tellorResponse) internal returns (uint) {
uint scaledTellorPrice = _scaleTellorPriceByDigits(_tellorResponse.value);
_storePrice(scaledTellorPrice);
return scaledTellorPrice;
}
function _storeChainlinkPrice(ChainlinkResponse memory _chainlinkResponse) internal returns (uint) {
uint scaledChainlinkPrice = _scaleChainlinkPriceByDigits(uint256(_chainlinkResponse.answer), _chainlinkResponse.decimals);
_storePrice(scaledChainlinkPrice);
return scaledChainlinkPrice;
}
// --- Oracle response wrapper functions ---
function _getCurrentTellorResponse() internal view returns (TellorResponse memory tellorResponse) {
try tellorCaller.getTellorCurrentValue(ETHUSD_TELLOR_REQ_ID) returns
(
bool ifRetrieve,
uint256 value,
uint256 _timestampRetrieved
)
{
// If call to Tellor succeeds, return the response and success = true
tellorResponse.ifRetrieve = ifRetrieve;
tellorResponse.value = value;
tellorResponse.timestamp = _timestampRetrieved;
tellorResponse.success = true;
return (tellorResponse);
}catch {
// If call to Tellor reverts, return a zero response with success = false
return (tellorResponse);
}
}
function _getCurrentChainlinkResponse() internal view returns (ChainlinkResponse memory chainlinkResponse) {
// First, try to get current decimal precision:
try priceAggregator.decimals() returns (uint8 decimals) {
// If call to Chainlink succeeds, record the current decimal precision
chainlinkResponse.decimals = decimals;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return chainlinkResponse;
}
// Secondly, try to get latest price data:
try priceAggregator.latestRoundData() returns
(
uint80 roundId,
int256 answer,
uint256 /* startedAt */,
uint256 timestamp,
uint80 /* answeredInRound */
)
{
// If call to Chainlink succeeds, return the response and success = true
chainlinkResponse.roundId = roundId;
chainlinkResponse.answer = answer;
chainlinkResponse.timestamp = timestamp;
chainlinkResponse.success = true;
return chainlinkResponse;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return chainlinkResponse;
}
}
function _getPrevChainlinkResponse(uint80 _currentRoundId, uint8 _currentDecimals) internal view returns (ChainlinkResponse memory prevChainlinkResponse) {
/*
* NOTE: Chainlink only offers a current decimals() value - there is no way to obtain the decimal precision used in a
* previous round. We assume the decimals used in the previous round are the same as the current round.
*/
// Try to get the price data from the previous round:
try priceAggregator.getRoundData(_currentRoundId - 1) returns
(
uint80 roundId,
int256 answer,
uint256 /* startedAt */,
uint256 timestamp,
uint80 /* answeredInRound */
)
{
// If call to Chainlink succeeds, return the response and success = true
prevChainlinkResponse.roundId = roundId;
prevChainlinkResponse.answer = answer;
prevChainlinkResponse.timestamp = timestamp;
prevChainlinkResponse.decimals = _currentDecimals;
prevChainlinkResponse.success = true;
return prevChainlinkResponse;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return prevChainlinkResponse;
}
}
}
|
Check for response call reverted Check for an invalid timeStamp that is 0, or in the future Check for zero price
|
function _tellorIsBroken(TellorResponse memory _response) internal view returns (bool) {
return false;
}
| 897,728
|
./full_match/80001/0xef280916594A36C96C48B626B483F14e3E86B921/sources/contracts/GeniosClub.sol
|
set current levelset current levelset current level
|
function updateG3X2(
address userAddr,
address refAddr,
uint8 level,
int x2
) private {
if (x2 == 0) {
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[0]]
.G3X2Matrix[level]
.FirstLevelRefs
.push(userAddr);
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[0]]
.G3X2Matrix[level]
.FirstTotalTeam++;
emit NewUserPlace(
userAddr,
Users[refAddr].G3X2Matrix[level].FirstLevelRefs[0],
1,
level,
uint8(
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[0]]
.G3X2Matrix[level]
.FirstLevelRefs
.length
)
);
emit NewUserPlace(
userAddr,
refAddr,
1,
level,
3 +
uint8(
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[0]]
.G3X2Matrix[level]
.FirstLevelRefs
.length
)
);
Users[userAddr].G3X2Matrix[level].CurrentRef = Users[refAddr]
.G3X2Matrix[level]
.FirstLevelRefs[0];
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[1]]
.G3X2Matrix[level]
.FirstLevelRefs
.push(userAddr);
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[1]]
.G3X2Matrix[level]
.FirstTotalTeam++;
emit NewUserPlace(
userAddr,
Users[refAddr].G3X2Matrix[level].FirstLevelRefs[1],
1,
level,
uint8(
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[1]]
.G3X2Matrix[level]
.FirstLevelRefs
.length
)
);
emit NewUserPlace(
userAddr,
refAddr,
1,
level,
6 +
uint8(
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[1]]
.G3X2Matrix[level]
.FirstLevelRefs
.length
)
);
Users[userAddr].G3X2Matrix[level].CurrentRef = Users[refAddr]
.G3X2Matrix[level]
.FirstLevelRefs[1];
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[2]]
.G3X2Matrix[level]
.FirstLevelRefs
.push(userAddr);
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[2]]
.G3X2Matrix[level]
.FirstTotalTeam++;
emit NewUserPlace(
userAddr,
Users[refAddr].G3X2Matrix[level].FirstLevelRefs[2],
1,
level,
uint8(
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[2]]
.G3X2Matrix[level]
.FirstLevelRefs
.length
)
);
emit NewUserPlace(
userAddr,
refAddr,
1,
level,
9 +
uint8(
Users[Users[refAddr].G3X2Matrix[level].FirstLevelRefs[2]]
.G3X2Matrix[level]
.FirstLevelRefs
.length
)
);
Users[userAddr].G3X2Matrix[level].CurrentRef = Users[refAddr]
.G3X2Matrix[level]
.FirstLevelRefs[2];
}
}
| 872,738
|
/**
*Submitted for verification at Etherscan.io on 2021-07-13
*/
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @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) {
// This method relies on 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;
}
/**
* @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");
require(isContract(target), "Address: Call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: Low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: Static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: Low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: Delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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);
}
}
}
}
/*
* @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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
string internal _uri;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: Balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: Owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory uri = _baseURI();
return
bytes(uri).length > 0
? string(abi.encodePacked(uri, _tokenId.toString(),".json"))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: Approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: Approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: Approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: Approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: Transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: Operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: Transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: Mint to the zero address");
require(!_exists(tokenId), "ERC721: Token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: Transfer of token that is not own");
require(to != address(0), "ERC721: Transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: Transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
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 () {
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;
}
}
contract BandRoyalty is Ownable(), ERC721("BAND Royalty","BD") {
address saleAddress;
mapping(uint256 => bool) internal notForSale;
mapping(address => bool) internal administrators;
event sale(address indexed _to, uint256 id);
modifier onlyAdministrator() {
require(administrators[msg.sender], "ERROR: You are not allowed");
_;
}
constructor() public {
saleAddress = 0xCA9700EFf4b99f13727Ca0254F8633A84AA3770b;
_uri = "https://ipfs.io/ipfs/QmPkpfqR2jy3C1nn44cSSocQk8ZUSm9AQH4knEzZ82kcwg/";
administrators[msg.sender] = true;
}
function buyBandRoyalyNft(uint256 _tokenId) payable public {
require(!notForSale[_tokenId],"ERROR: This token has already purchased");
require(msg.value >= 1 ether && msg.value <= 25 ether, "ERROR: Wrong price range");
require(msg.value == choosePrice(_tokenId),"ERROR: You have provide wrong price against the tokenid");
require(_tokenId <= 3000,"ERROR: Only 3000 limit");
_mint(_msgSender(),_tokenId);
notForSale[_tokenId] = true;
payable(saleAddress).transfer(msg.value);
emit sale(msg.sender,_tokenId);
}
function addPurchaseAndTreasuryItems(uint256[] memory _ids) onlyAdministrator public {
for(uint256 i=0; i<_ids.length; i++){
notForSale[_ids[i]] = true;
emit sale(address(0),_ids[i]);
}
}
function preMintNftBatch(uint256[] memory _ids, address[] memory _to) onlyAdministrator public {
require(_ids.length == _to.length,"ERROR: Wrong address or id");
for(uint256 i=0; i<_ids.length; i++){
_mint(_to[i],_ids[i]);
}
}
function preMintNft(uint256 _id, address _to) onlyAdministrator public {
_mint(_to,_id);
}
function addAdministrators(address _address) public onlyOwner {
administrators[_address] = true;
}
function removeAdministrators(address _address) public onlyOwner {
administrators[_address] = false;
}
function changeSaleAddress(address _newAddress) public onlyOwner {
saleAddress = _newAddress;
}
function choosePrice(uint256 _tokenId) internal returns(uint256){
if (_tokenId == 1) {
return 25 ether;
}
else if (_tokenId == 2) {
return 20 ether;
}
else if (_tokenId == 3) {
return 15 ether;
}
else if (_tokenId >= 4 && _tokenId <= 25) {
return 10 ether;
}
else if (_tokenId >= 26 && _tokenId <= 250) {
return 7 ether;
}
else if (_tokenId >= 251 && _tokenId <= 750) {
return 5 ether;
}
else if (_tokenId >= 751 && _tokenId <= 1500) {
return 3 ether;
}
else if (_tokenId >= 1500 && _tokenId <= 3000) {
return 1 ether;
}
}
}
|
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but performing a static call. _Available since v3.3._/
|
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: Low-level static call failed");
}
| 7,792,891
|
pragma solidity ^0.4.15;
/*
Bancor Converter v0.6
The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves.
ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on
the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract.
The converter is upgradable (just like any SmartTokenController).
WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits
or with very small numbers because of precision loss
Open issues:
- Front-running attacks are currently mitigated by the following mechanisms:
- minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction
- gas price limit prevents users from having control over the order of execution
Other potential solutions might include a commit/reveal based schemes
- Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct
*/
/*
Token Holder interface
*/
/*
Owned contract interface
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint128 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint128 _x, uint128 _y) internal constant returns (uint128) {
uint128 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint128 _x, uint128 _y) internal constant returns (uint128) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint128 _x, uint128 _y) internal constant returns (uint128) {
uint128 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint128 _amount) public;
}
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) {}
function symbol() public constant returns (string) {}
function decimals() public constant returns (uint8) {}
function totalSupply() public constant returns (uint128) {}
function balanceOf(address _owner) public constant returns (uint128) {_owner;}
function allowance(address _owner, address _spender) public constant returns (uint128) {_owner;
_spender;}
function transfer(address _to, uint128 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint128 _value) public returns (bool success);
function approve(address _spender, uint128 _value) public returns (bool success);
}
/*
EIP228 Token Converter interface
*/
contract ITokenConverter {
function convertibleTokenCount() public constant returns (uint16);
function convertibleToken(uint16 _tokenIndex) public constant returns (address);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint128 _amount) public constant returns (uint128);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint128 _amount, uint128 _minReturn) public returns (uint128);
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint128 _amount, uint128 _minReturn) public returns (uint128);
}
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint128 _amount) public;
function destroy(address _from, uint128 _amount) public;
}
/*
Bancor Quick Converter interface
*/
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint128 _amount, uint128 _minReturn) public payable returns (uint128);
function convertFor(IERC20Token[] _path, uint128 _amount, uint128 _minReturn, address _for) public payable returns (uint128);
}
/*
Bancor Gas Price Limit interface
*/
contract IBancorGasPriceLimit {
function gasPrice() public constant returns (uint128) {}
}
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint128 _supply, uint128 _connectorBalance, uint32 _connectorWeight, uint128 _depositAmount) public constant returns (uint128);
function calculateSaleReturn(uint128 _supply, uint128 _connectorBalance, uint32 _connectorWeight, uint128 _sellAmount) public constant returns (uint128);
}
/*
Bancor Converter Extensions interface
*/
contract IBancorConverterExtensions {
function formula() public constant returns (IBancorFormula) {}
function gasPriceLimit() public constant returns (IBancorGasPriceLimit) {}
function quickConverter() public constant returns (IBancorQuickConverter) {}
}
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint128 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
The smart token controller is an upgradable part of the smart token that allows
more functionality as well as fixes for bugs/exploits.
Once it accepts ownership of the token, it becomes the token's sole controller
that can execute any of its functions.
To upgrade the controller, ownership must be transferred to a new controller, along with
any relevant data.
The smart token must be set on construction and cannot be changed afterwards.
Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access.
Note that the controller can transfer token ownership to a new controller that
doesn't allow executing any function on the token, for a trustless solution.
Doing that will also remove the owner's ability to upgrade the controller.
*/
contract SmartTokenController is TokenHolder {
ISmartToken public token; // smart token
/**
@dev constructor
*/
function SmartTokenController(ISmartToken _token)
validAddress(_token)
{
token = _token;
}
// ensures that the controller is the token's owner
modifier active() {
assert(token.owner() == address(this));
_;
}
// ensures that the controller is not the token's owner
modifier inactive() {
assert(token.owner() != address(this));
_;
}
/**
@dev allows transferring the token ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new token owner
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
/**
@dev used by a new owner to accept a token ownership transfer
can only be called by the contract owner
*/
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
/**
@dev disables/enables token transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
/**
@dev withdraws tokens held by the token and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawFromToken(IERC20Token _token, address _to, uint128 _amount) public ownerOnly {
ITokenHolder(token).withdrawTokens(_token, _to, _amount);
}
}
/*
Provides support and utilities for contract management
*/
contract Managed {
address public manager;
address public newManager;
event ManagerUpdate(address _prevManager, address _newManager);
/**
@dev constructor
*/
function Managed() {
manager = msg.sender;
}
// allows execution by the manager only
modifier managerOnly {
assert(msg.sender == manager);
_;
}
/**
@dev allows transferring the contract management
the new manager still needs to accept the transfer
can only be called by the contract manager
@param _newManager new contract manager
*/
function transferManagement(address _newManager) public managerOnly {
require(_newManager != manager);
newManager = _newManager;
}
/**
@dev used by a new manager to accept a management transfer
*/
function acceptManagement() public {
require(msg.sender == newManager);
ManagerUpdate(manager, newManager);
manager = newManager;
newManager = 0x0;
}
}
contract BancorConverter is ITokenConverter, SmartTokenController, Managed {
uint32 private constant MAX_WEIGHT = 1000000;
uint32 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint128 virtualBalance; // connector virtual balance
uint32 weight; // connector weight, represented in ppm, 1-1000000
bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not
bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner
bool isSet; // used to tell if the mapping element is defined
}
string public version = '0.6';
string public converterType = 'bancor';
IBancorConverterExtensions public extensions; // bancor converter extensions contract
IERC20Token[] public connectorTokens; // ERC20 standard token addresses
IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH
mapping(address => Connector) public connectors; // connector token addresses -> connector data
uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100%
uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public conversionsEnabled = true; // true if token conversions is enabled, false if not
// triggered when a conversion between two tokens occurs (TokenConverter event)
event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint128 _amount, uint128 _return,
uint128 _currentPriceN, uint128 _currentPriceD);
// triggered when the conversion fee is updated
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
@dev constructor
@param _token smart token governed by the converter
@param _extensions address of a bancor converter extensions contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
*/
function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight)
SmartTokenController(_token)
validAddress(_extensions)
validMaxConversionFee(_maxConversionFee)
{
extensions = _extensions;
maxConversionFee = _maxConversionFee;
if (address(_connectorToken) != 0x0)
addConnector(_connectorToken, _connectorWeight, false);
}
// validates a connector token address - verifies that the address belongs to one of the connector tokens
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
// validates a token address - verifies that the address belongs to one of the convertible tokens
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
// verifies that the gas price is lower than the universal limit
modifier validGasPrice() {
assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice());
_;
}
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
_;
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
// validates connector weight range
modifier validConnectorWeight(uint32 _weight) {
require(_weight > 0 && _weight <= MAX_WEIGHT);
_;
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
// allows execution only when conversions aren't disabled
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
/**
@dev returns the number of connector tokens defined
@return number of connector tokens
*/
function connectorTokenCount() public constant returns (uint16) {
return uint16(connectorTokens.length);
}
/**
@dev returns the number of convertible tokens supported by the contract
note that the number of convertible tokens is the number of connector token, plus 1 (that represents the smart token)
@return number of convertible tokens
*/
function convertibleTokenCount() public constant returns (uint16) {
return connectorTokenCount() + 1;
}
/**
@dev given a convertible token index, returns its contract address
@param _tokenIndex convertible token index
@return convertible token address
*/
function convertibleToken(uint16 _tokenIndex) public constant returns (address) {
if (_tokenIndex == 0)
return token;
return connectorTokens[_tokenIndex - 1];
}
/*
@dev allows the owner to update the extensions contract address
@param _extensions address of a bancor converter extensions contract
*/
function setExtensions(IBancorConverterExtensions _extensions)
public
ownerOnly
validAddress(_extensions)
notThis(_extensions)
{
extensions = _extensions;
}
/*
@dev allows the manager to update the quick buy path
@param _path new quick buy path, see conversion path format in the BancorQuickConverter contract
*/
function setQuickBuyPath(IERC20Token[] _path)
public
ownerOnly
validConversionPath(_path)
{
quickBuyPath = _path;
}
/*
@dev allows the manager to clear the quick buy path
*/
function clearQuickBuyPath() public ownerOnly {
quickBuyPath.length = 0;
}
/**
@dev returns the length of the quick buy path array
@return quick buy path length
*/
function getQuickBuyPathLength() public constant returns (uint128) {
return uint128(quickBuyPath.length);
}
/**
@dev disables the entire conversion functionality
this is a safety mechanism in case of a emergency
can only be called by the manager
@param _disable true to disable conversions, false to re-enable them
*/
function disableConversions(bool _disable) public managerOnly {
conversionsEnabled = !_disable;
}
/**
@dev updates the current conversion fee
can only be called by the manager
@param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee)
public
managerOnly
validConversionFee(_conversionFee)
{
ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/*
@dev returns the conversion fee amount for a given return amount
@return conversion fee amount
*/
function getConversionFeeAmount(uint128 _amount) public constant returns (uint128) {
return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE;
}
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
*/
function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT);
// validate input
connectors[_token].virtualBalance = 0;
connectors[_token].weight = _weight;
connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
connectors[_token].isPurchaseEnabled = true;
connectors[_token].isSet = true;
connectorTokens.push(_token);
totalConnectorWeight += _weight;
}
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
@param _virtualBalance new connector's virtual balance
*/
function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint128 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT);
// validate input
totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
connector.weight = _weight;
connector.isVirtualBalanceEnabled = _enableVirtualBalance;
connector.virtualBalance = _virtualBalance;
}
/**
@dev disables purchasing with the given connector token in case the connector token got compromised
can only be called by the owner
note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
@param _connectorToken connector token contract address
@param _disable true to disable the token, false to re-enable it
*/
function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
public
ownerOnly
validConnector(_connectorToken)
{
connectors[_connectorToken].isPurchaseEnabled = !_disable;
}
/**
@dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
@param _connectorToken connector token contract address
@return connector balance
*/
function getConnectorBalance(IERC20Token _connectorToken)
public
constant
validConnector(_connectorToken)
returns (uint128)
{
Connector storage connector = connectors[_connectorToken];
return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
}
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint128 _amount) public constant returns (uint128) {
require(_fromToken != _toToken);
// validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 connectors
uint128 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
}
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/
function getPurchaseReturn(IERC20Token _connectorToken, uint128 _depositAmount)
public
constant
active
validConnector(_connectorToken)
returns (uint128)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled);
// validate input
uint128 tokenSupply = token.totalSupply();
uint128 connectorBalance = getConnectorBalance(_connectorToken);
uint128 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
// deduct the fee from the return amount
uint128 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint128 _sellAmount) public constant returns (uint128) {
return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply());
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint128 _amount, uint128 _minReturn) public returns (uint128) {
require(_fromToken != _toToken);
// validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
// conversion between 2 connectors
uint128 purchaseAmount = buy(_fromToken, _amount, 1);
return sell(_toToken, purchaseAmount, _minReturn);
}
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return buy return amount
*/
function buy(IERC20Token _connectorToken, uint128 _depositAmount, uint128 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint128)
{
uint128 amount = getPurchaseReturn(_connectorToken, _depositAmount);
assert(amount != 0 && amount >= _minReturn);
// ensure the trade gives something in return and meets the minimum requested amount
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
// transfer _depositAmount funds from the caller in the connector token
//assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
dispatchConversionEvent(_connectorToken, _depositAmount, amount, true);
return amount;
}
function checkTransfer(IERC20Token _connectorToken, uint128 _depositAmount, uint128 _minReturn) returns (bool){
assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
//token.issue(msg.sender, _depositAmount);
return true;
}
/**
@dev sells the token by withdrawing from one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
@return sell return amount
*/
function sell(IERC20Token _connectorToken, uint128 _sellAmount, uint128 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint128)
{
require(_sellAmount <= token.balanceOf(msg.sender));
// validate input
uint128 amount = getSaleReturn(_connectorToken, _sellAmount);
assert(amount != 0 && amount >= _minReturn);
// ensure the trade gives something in return and meets the minimum requested amount
uint128 tokenSupply = token.totalSupply();
uint128 connectorBalance = getConnectorBalance(_connectorToken);
// ensure that the trade will only deplete the connector if the total supply is depleted as well
assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, amount);
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
//assert(_connectorToken.transfer(msg.sender, amount));
dispatchConversionEvent(_connectorToken, _sellAmount, amount, false);
return amount;
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorQuickConverter contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function quickConvert(IERC20Token[] _path, uint128 _amount, uint128 _minReturn)
public
payable
validConversionPath(_path)
returns (uint128)
{
IERC20Token fromToken = _path[0];
IBancorQuickConverter quickConverter = extensions.quickConverter();
// we need to transfer the source tokens from the caller to the quick converter,
// so it can execute the conversion on behalf of the caller
if (uint128(msg.value) == 0) {
// not ETH, send the source tokens to the quick converter
// if the token is the smart token, no allowance is required - destroy the tokens from the caller and issue them to the quick converter
if (fromToken == token) {
token.destroy(msg.sender, _amount);
// destroy _amount tokens from the caller's balance in the smart token
token.issue(quickConverter, _amount);
// issue _amount new tokens to the quick converter
}
else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the quick converter
assert(fromToken.transferFrom(msg.sender, quickConverter, _amount));
}
}
// execute the conversion and pass on the ETH with the call
return quickConverter.convertFor.value(uint128(msg.value))(_path, _amount, _minReturn, msg.sender);
}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint128 _amount, uint128 _minReturn) public returns (uint128) {
return convert(_fromToken, _toToken, _amount, _minReturn);
}
/**
@dev utility, returns the expected return for selling the token for one of its connector tokens, given a total supply override
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _totalSupply total token supply, overrides the actual token total supply when calculating the return
@return sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint128 _sellAmount, uint128 _totalSupply)
private
constant
active
validConnector(_connectorToken)
greaterThanZero(_totalSupply)
returns (uint128)
{
Connector storage connector = connectors[_connectorToken];
uint128 connectorBalance = getConnectorBalance(_connectorToken);
uint128 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount);
// deduct the fee from the return amount
uint128 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev helper, dispatches the Conversion event
The function also takes the tokens' decimals into account when calculating the current price
@param _connectorToken connector token contract address
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
@param isPurchase true if it's a purchase, false if it's a sale
*/
function dispatchConversionEvent(IERC20Token _connectorToken, uint128 _amount, uint128 _returnAmount, bool isPurchase) private {
Connector storage connector = connectors[_connectorToken];
// calculate the new price using the simple price formula
// price = connector balance / (supply * weight)
// weight is represented in ppm, so multiplying by 1000000
uint128 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT);
uint128 tokenAmount = safeMul(token.totalSupply(), connector.weight);
// normalize values
uint8 tokenDecimals = token.decimals();
uint128 decimals = 10;
uint8 connectorTokenDecimals = _connectorToken.decimals();
if (tokenDecimals != connectorTokenDecimals) {
if (tokenDecimals > connectorTokenDecimals)
connectorAmount = safeMul(connectorAmount, uint128(decimals ** uint128(tokenDecimals - connectorTokenDecimals)));
else
tokenAmount = safeMul(tokenAmount, uint128(decimals ** uint128(connectorTokenDecimals - tokenDecimals)));
}
// if (isPurchase)
// Conversion(_connectorToken, token, msg.sender, _amount, _returnAmount, connectorAmount, tokenAmount);
// else
// Conversion(token, _connectorToken, msg.sender, _amount, _returnAmount, tokenAmount, connectorAmount);
}
/**
@dev fallback, buys the smart token with ETH
note that the purchase will use the price at the time of the purchase
*/
function() payable {
quickConvert(quickBuyPath, uint128(msg.value), 1);
}
}
/**
@dev the BancorConverterExtensions contract is an owned contract that serves as a single point of access
to the BancorFormula, BancorGasPriceLimit and BancorQuickConverter contracts from all BancorConverter contract instances.
it allows upgrading these contracts without the need to update each and every
BancorConverter contract instance individually.
*/
contract BancorConverterExtensions is IBancorConverterExtensions, TokenHolder {
IBancorFormula public formula; // bancor calculation formula contract
IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract
IBancorQuickConverter public quickConverter; // bancor quick converter contract
/**
@dev constructor
@param _formula address of a bancor formula contract
@param _gasPriceLimit address of a bancor gas price limit contract
@param _quickConverter address of a bancor quick converter contract
*/
function BancorConverterExtensions(IBancorFormula _formula, IBancorGasPriceLimit _gasPriceLimit, IBancorQuickConverter _quickConverter)
validAddress(_formula)
validAddress(_gasPriceLimit)
validAddress(_quickConverter)
{
formula = _formula;
gasPriceLimit = _gasPriceLimit;
quickConverter = _quickConverter;
}
/*
@dev allows the owner to update the formula contract address
@param _formula address of a bancor formula contract
*/
function setFormula(IBancorFormula _formula)
public
ownerOnly
validAddress(_formula)
notThis(_formula)
{
formula = _formula;
}
/*
@dev allows the owner to update the gas price limit contract address
@param _gasPriceLimit address of a bancor gas price limit contract
*/
function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit)
public
ownerOnly
validAddress(_gasPriceLimit)
notThis(_gasPriceLimit)
{
gasPriceLimit = _gasPriceLimit;
}
/*
@dev allows the owner to update the quick converter contract address
@param _quickConverter address of a bancor quick converter contract
*/
function setQuickConverter(IBancorQuickConverter _quickConverter)
public
ownerOnly
validAddress(_quickConverter)
notThis(_quickConverter)
{
quickConverter = _quickConverter;
}
}
contract BancorFormula is IBancorFormula, Utils {
string public version = '0.3';
uint128 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 1;
uint8 private constant MAX_PRECISION = 63;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below.
*/
uint128 private constant FIXED_1 = 0x08000000000000000;
uint128 private constant FIXED_2 = 0x10000000000000000;
uint128 private constant MAX_NUM = 0x1ffffffffffffffff;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintLn2ScalingFactors.py', run it and paste the results below.
*/
uint128 private constant LN2_MANTISSA = 0x58b90bfbe8e7bcd;
uint8 private constant LN2_EXPONENT = 59;
/**
The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them:
Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below.
*/
uint128[64] private maxExpArray;
function BancorFormula() {
// maxExpArray[ 0] = 0x1ffffffffffffffff;
maxExpArray[1] = 0x1bfffffffffffffff;
maxExpArray[2] = 0x15fffffffffffffff;
maxExpArray[3] = 0x10fffffffffffffff;
maxExpArray[4] = 0x0d7ffffffffffffff;
maxExpArray[5] = 0x09fffffffffffffff;
maxExpArray[6] = 0x079ffffffffffffff;
maxExpArray[7] = 0x059ffffffffffffff;
maxExpArray[8] = 0x040ffffffffffffff;
maxExpArray[9] = 0x02f7fffffffffffff;
maxExpArray[10] = 0x021ffffffffffffff;
maxExpArray[11] = 0x0185fffffffffffff;
maxExpArray[12] = 0x01157ffffffffffff;
maxExpArray[13] = 0x00c6bffffffffffff;
maxExpArray[14] = 0x008c7ffffffffffff;
maxExpArray[15] = 0x0063effffffffffff;
maxExpArray[16] = 0x0046a7fffffffffff;
maxExpArray[17] = 0x003247fffffffffff;
maxExpArray[18] = 0x00238dfffffffffff;
maxExpArray[19] = 0x001923fffffffffff;
maxExpArray[20] = 0x0011c6fffffffffff;
maxExpArray[21] = 0x000c91fffffffffff;
maxExpArray[22] = 0x0008e37ffffffffff;
maxExpArray[23] = 0x000648effffffffff;
maxExpArray[24] = 0x000471b7fffffffff;
maxExpArray[25] = 0x00032477fffffffff;
maxExpArray[26] = 0x000238d9fffffffff;
maxExpArray[27] = 0x0001923bfffffffff;
maxExpArray[28] = 0x00011c6c7ffffffff;
maxExpArray[29] = 0x0000c91dfffffffff;
maxExpArray[30] = 0x00008e361ffffffff;
maxExpArray[31] = 0x0000648efffffffff;
maxExpArray[32] = 0x0000471b07fffffff;
maxExpArray[33] = 0x000032477bfffffff;
maxExpArray[34] = 0x0000238d83fffffff;
maxExpArray[35] = 0x00001923bdfffffff;
maxExpArray[36] = 0x000011c6c17ffffff;
maxExpArray[37] = 0x00000c91debffffff;
maxExpArray[38] = 0x000008e360bffffff;
maxExpArray[39] = 0x00000648ef5ffffff;
maxExpArray[40] = 0x00000471b05ffffff;
maxExpArray[41] = 0x0000032477affffff;
maxExpArray[42] = 0x00000238d82dfffff;
maxExpArray[43] = 0x000001923bd7fffff;
maxExpArray[44] = 0x0000011c6c16fffff;
maxExpArray[45] = 0x000000c91debfffff;
maxExpArray[46] = 0x0000008e360b5ffff;
maxExpArray[47] = 0x000000648ef5fffff;
maxExpArray[48] = 0x000000471b05affff;
maxExpArray[49] = 0x00000032477afffff;
maxExpArray[50] = 0x000000238d82d7fff;
maxExpArray[51] = 0x0000001923bd7efff;
maxExpArray[52] = 0x00000011c6c16b7ff;
maxExpArray[53] = 0x0000000c91debf3ff;
maxExpArray[54] = 0x00000008e360b59ff;
maxExpArray[55] = 0x0000000648ef5f8ff;
maxExpArray[56] = 0x0000000471b05acff;
maxExpArray[57] = 0x000000032477afc7f;
maxExpArray[58] = 0x0000000238d82d65f;
maxExpArray[59] = 0x00000001923bd7e2f;
maxExpArray[60] = 0x000000011c6c16b2f;
maxExpArray[61] = 0x00000000c91debf13;
maxExpArray[62] = 0x000000008e360b597;
maxExpArray[63] = 0x00000000648ef5f89;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint128 _supply, uint128 _connectorBalance, uint32 _connectorWeight, uint128 _depositAmount) public constant returns (uint128) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_supply, _depositAmount) / _connectorBalance;
uint128 result;
uint8 precision;
uint128 baseN = safeAdd(_depositAmount, _connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint128 temp = safeMul(_supply, result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint128 _supply, uint128 _connectorBalance, uint32 _connectorWeight, uint128 _sellAmount) public constant returns (uint128) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_connectorBalance, _sellAmount) / _supply;
uint128 result;
uint8 precision;
uint128 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint128 temp1 = safeMul(_connectorBalance, result);
uint128 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (ln(base) * exp)".
The value of "ln(base)" is represented with an integer slightly smaller than "ln(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 128 bits in any of the intermediate computations.
*/
function power(uint128 _baseN, uint128 _baseD, uint32 _expN, uint32 _expD) internal constant returns (uint128, uint8) {
uint128 lnBaseTimesExp = ln(_baseN, _baseD) * _expN / _expD;
uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
return (fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
/**
Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:
- The numerator is a value between 1 and 2 ^ (128 - MAX_PRECISION) - 1
- The denominator is a value between 1 and 2 ^ (128 - MAX_PRECISION) - 1
- The output is a value between 0 and floor(ln(2 ^ (128 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
*/
function ln(uint128 _numerator, uint128 _denominator) internal constant returns (uint128) {
assert(_numerator <= MAX_NUM);
uint128 res = 0;
uint128 x = _numerator * FIXED_1 / _denominator;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count;
// now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1;
// now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1;
// now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return (res * LN2_MANTISSA) >> LN2_EXPONENT;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint128 _n) internal constant returns (uint8) {
uint8 res = 0;
if (_n < 128) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 64; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint128 _x) internal constant returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
assert(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionFixedExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function fixedExp(uint128 _x, uint8 _precision) internal constant returns (uint128) {
uint128 xi = _x;
uint128 res = 0;
xi = (xi * _x) >> _precision;
res += xi * 0x03442c4e6074a82f1797f72ac0000000;
// add x^2 * (33! / 2!)
xi = (xi * _x) >> _precision;
res += xi * 0x0116b96f757c380fb287fd0e40000000;
// add x^3 * (33! / 3!)
xi = (xi * _x) >> _precision;
res += xi * 0x0045ae5bdd5f0e03eca1ff4390000000;
// add x^4 * (33! / 4!)
xi = (xi * _x) >> _precision;
res += xi * 0x000defabf91302cd95b9ffda50000000;
// add x^5 * (33! / 5!)
xi = (xi * _x) >> _precision;
res += xi * 0x0002529ca9832b22439efff9b8000000;
// add x^6 * (33! / 6!)
xi = (xi * _x) >> _precision;
res += xi * 0x000054f1cf12bd04e516b6da88000000;
// add x^7 * (33! / 7!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000a9e39e257a09ca2d6db51000000;
// add x^8 * (33! / 8!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000012e066e7b839fa050c309000000;
// add x^9 * (33! / 9!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000001e33d7d926c329a1ad1a800000;
// add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000002bee513bdb4a6b19b5f800000;
// add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000003a9316fa79b88eccf2a00000;
// add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000048177ebe1fa812375200000;
// add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000005263fe90242dcbacf00000;
// add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000057e22099c030d94100000;
// add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000057e22099c030d9410000;
// add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000052b6b54569976310000;
// add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000004985f67696bf748000;
// add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000003dea12ea99e498000;
// add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000031880f2214b6e000;
// add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000025bcff56eb36000;
// add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000001b722e10ab1000;
// add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000001317c70077000;
// add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000cba84aafa00;
// add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000082573a0a00;
// add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000005035ad900;
// add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000002f881b00;
// add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000001b29340;
// add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000000000efc40;
// add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000007fe0;
// add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000420;
// add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000021;
// add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000001;
// add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision);
// divide by 33! and then add x^1 / 1! + x^0 / 0!
}
}
/*
The BancorGasPriceLimit contract serves as an extra front-running attack mitigation mechanism.
It sets a maximum gas price on all bancor conversions, which prevents users from "cutting in line"
in order to front-run other transactions.
The gas price limit is universal to all converters and it can be updated by the owner to be in line
with the network's current gas price.
*/
contract BancorGasPriceLimit is IBancorGasPriceLimit, Owned, Utils {
uint128 public gasPrice = 0 wei; // maximum gas price for bancor transactions
/**
@dev constructor
@param _gasPrice gas price limit
*/
function BancorGasPriceLimit(uint128 _gasPrice)
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
/*
@dev allows the owner to update the gas price limit
@param _gasPrice new gas price limit
*/
function setGasPrice(uint128 _gasPrice)
public
ownerOnly
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
}
/*
BancorPriceFloor v0.1
The bancor price floor contract is a simple contract that allows selling smart tokens for a constant ETH price
'Owned' is specified here for readability reasons
*/
contract BancorPriceFloor is Owned, TokenHolder {
uint128 public constant TOKEN_PRICE_N = 1; // crowdsale price in wei (numerator)
uint128 public constant TOKEN_PRICE_D = 100; // crowdsale price in wei (denominator)
string public version = '0.1';
ISmartToken public token; // smart token the contract allows selling
/**
@dev constructor
@param _token smart token the contract allows selling
*/
function BancorPriceFloor(ISmartToken _token)
validAddress(_token)
{
token = _token;
}
/**
@dev sells the smart token for ETH
note that the function will sell the full allowance amount
@return ETH sent in return
*/
function sell() public returns (uint128 amount) {
uint128 allowance = token.allowance(msg.sender, this);
// get the full allowance amount
assert(token.transferFrom(msg.sender, this, allowance));
// transfer all tokens from the sender to the contract
uint128 etherValue = safeMul(allowance, TOKEN_PRICE_N) / TOKEN_PRICE_D;
// calculate ETH value of the tokens
msg.sender.transfer(etherValue);
// send the ETH amount to the seller
return etherValue;
}
/**
@dev withdraws ETH from the contract
@param _amount amount of ETH to withdraw
*/
function withdraw(uint128 _amount) public ownerOnly {
msg.sender.transfer(_amount);
// send the amount
}
/**
@dev deposits ETH in the contract
*/
function() public payable {
}
}
/*
The BancorQuickConverter contract provides allows converting between any token in the
bancor network in a single transaction.
A note on conversion paths -
Conversion path is a data structure that's used when converting a token to another token in the bancor network
when the conversion cannot necessarily be done by single converter and might require multiple 'hops'.
The path defines which converters should be used and what kind of conversion should be done in each step.
The path format doesn't include complex structure and instead, it is represented by a single array
in which each 'hop' is represented by a 2-tuple - smart token & to token.
In addition, the first element is always the source token.
The smart token is only used as a pointer to a converter (since converter addresses are more likely to change).
Format:
[source token, smart token, to token, smart token, to token...]
*/
contract BancorQuickConverter is IBancorQuickConverter, TokenHolder {
mapping(address => bool) public etherTokens; // list of all supported ether tokens
/**
@dev constructor
*/
function BancorQuickConverter() {
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
/**
@dev allows the owner to register/unregister ether tokens
@param _token ether token contract address
@param _register true to register, false to unregister
*/
function registerEtherToken(IEtherToken _token, bool _register)
public
ownerOnly
validAddress(_token)
notThis(_token)
{
etherTokens[_token] = _register;
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens to a target account
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function convertFor(IERC20Token[] _path, uint128 _amount, uint128 _minReturn, address _for)
public
payable
validConversionPath(_path)
returns (uint128)
{
// if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token
IERC20Token fromToken = _path[0];
require(uint128(msg.value) == 0 || (_amount == uint128(msg.value) && etherTokens[fromToken]));
// if ETH was sent with the call, the source is an ether token - deposit the ETH in it
// otherwise, we assume we already have the tokens
if (uint128(msg.value) > 0)
IEtherToken(fromToken).deposit.value(uint128(msg.value))();
// iterate over the conversion path
IERC20Token toToken = _path[iterateConversionPath(_path, _amount, _minReturn)];
// finished the conversion, transfer the funds to the target account
// if the target token is an ether token, withdraw the tokens and send them as ETH
// otherwise, transfer the tokens as is
if (etherTokens[toToken])
IEtherToken(toToken).withdrawTo(_for, _amount);
else
assert(toToken.transfer(_for, _amount));
return _amount;
}
function iterateConversionPath(IERC20Token[] _path, uint128 _amount, uint128 _minReturn)
private
returns (uint128)
{
uint128 to = 2;
for (; to < _path.length; to += 2) {
// The following variables have been replaced with expressions to save stack space
/*
IERC20Token fromToken = _path[to - 2];
ISmartToken smartToken = ISmartToken(_path[to - 1]);
IERC20Token toToken = _path[to];
*/
ITokenConverter converter = ITokenConverter(ISmartToken(_path[to - 1]).owner());
// if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request
if (ISmartToken(_path[to - 1]) != _path[to - 2])
ensureAllowance(_path[to - 2], converter, _amount);
// make the conversion - if it's the last one, also provide the minimum return value
_amount = converter.change(_path[to - 2], _path[to], _amount, to == _path.length - 1 ? _minReturn : 1);
}
return to;
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens to a target account
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function claimAndConvertFor(IERC20Token[] _path, uint128 _amount, uint128 _minReturn, address _for) public returns (uint128) {
// we need to transfer the tokens from the caller to the converter before we follow
// the conversion path, to allow it to execute the conversion on behalf of the caller
// note: we assume we already have allowance
IERC20Token fromToken = _path[0];
assert(fromToken.transferFrom(msg.sender, this, _amount));
return convertFor(_path, _amount, _minReturn, _for);
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens back to the sender
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function convert(IERC20Token[] _path, uint128 _amount, uint128 _minReturn) public payable returns (uint128) {
return convertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens back to the sender
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function claimAndConvert(IERC20Token[] _path, uint128 _amount, uint128 _minReturn) public returns (uint128) {
return claimAndConvertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev utility, checks whether allowance for the given spender exists and approves one if it doesn't
@param _token token to check the allowance in
@param _spender approved address
@param _value allowance amount
*/
function ensureAllowance(IERC20Token _token, address _spender, uint128 _value) private {
// check if allowance for the given amount already exists
if (_token.allowance(this, _spender) >= _value)
return;
// if the allowance is nonzero, must reset it to 0 first
if (_token.allowance(this, _spender) != 0)
assert(_token.approve(_spender, 0));
// approve the new allowance
assert(_token.approve(_spender, _value));
}
}
/*
Crowdsale v0.1
The crowdsale version of the smart token controller, allows contributing ether in exchange for Bancor tokens
The price remains fixed for the entire duration of the crowdsale
Note that 20% of the contributions are the BNT token's ETH connector balance
*/
contract CrowdsaleController is SmartTokenController {
uint128 public constant DURATION = 14 days; // crowdsale duration
uint128 public constant TOKEN_PRICE_N = 1; // initial price in wei (numerator)
uint128 public constant TOKEN_PRICE_D = 100; // initial price in wei (denominator)
uint128 public constant BTCS_ETHER_CAP = 50000 ether; // maximum bitcoin suisse ether contribution
uint128 public constant MAX_GAS_PRICE = 50000000000 wei; // maximum gas price for contribution transactions
string public version = '0.1';
uint128 public startTime = 0; // crowdsale start time (in seconds)
uint128 public endTime = 0; // crowdsale end time (in seconds)
uint128 public totalEtherCap = 1000000 ether; // current ether contribution cap, initialized with a temp value as a safety mechanism until the real cap is revealed
uint128 public totalEtherContributed = 0; // ether contributed so far
bytes32 public realEtherCapHash; // ensures that the real cap is predefined on deployment and cannot be changed later
address public beneficiary = 0x0; // address to receive all ether contributions
address public btcs = 0x0; // bitcoin suisse address
// triggered on each contribution
event Contribution(address indexed _contributor, uint128 _amount, uint128 _return);
/**
@dev constructor
@param _token smart token the crowdsale is for
@param _startTime crowdsale start time
@param _beneficiary address to receive all ether contributions
@param _btcs bitcoin suisse address
*/
function CrowdsaleController(ISmartToken _token, uint128 _startTime, address _beneficiary, address _btcs, bytes32 _realEtherCapHash)
SmartTokenController(_token)
validAddress(_beneficiary)
validAddress(_btcs)
earlierThan(_startTime)
greaterThanZero(uint128(_realEtherCapHash))
{
startTime = _startTime;
endTime = startTime + DURATION;
beneficiary = _beneficiary;
btcs = _btcs;
realEtherCapHash = _realEtherCapHash;
}
// verifies that the gas price is lower than 50 gwei
modifier validGasPrice() {
assert(tx.gasprice <= MAX_GAS_PRICE);
_;
}
// verifies that the ether cap is valid based on the key provided
modifier validEtherCap(uint128 _cap, uint128 _key) {
require(computeRealCap(_cap, _key) == realEtherCapHash);
_;
}
// ensures that it's earlier than the given time
modifier earlierThan(uint128 _time) {
assert(now < _time);
_;
}
// ensures that the current time is between _startTime (inclusive) and _endTime (exclusive)
modifier between(uint128 _startTime, uint128 _endTime) {
assert(now >= _startTime && now < _endTime);
_;
}
// ensures that the sender is bitcoin suisse
modifier btcsOnly() {
assert(msg.sender == btcs);
_;
}
// ensures that we didn't reach the ether cap
modifier etherCapNotReached(uint128 _contribution) {
assert(safeAdd(totalEtherContributed, _contribution) <= totalEtherCap);
_;
}
// ensures that we didn't reach the bitcoin suisse ether cap
modifier btcsEtherCapNotReached(uint128 _ethContribution) {
assert(safeAdd(totalEtherContributed, _ethContribution) <= BTCS_ETHER_CAP);
_;
}
/**
@dev computes the real cap based on the given cap & key
@param _cap cap
@param _key key used to compute the cap hash
@return computed real cap hash
*/
function computeRealCap(uint128 _cap, uint128 _key) public constant returns (bytes32) {
return keccak256(_cap, _key);
}
/**
@dev enables the real cap defined on deployment
@param _cap predefined cap
@param _key key used to compute the cap hash
*/
function enableRealCap(uint128 _cap, uint128 _key)
public
ownerOnly
active
between(startTime, endTime)
validEtherCap(_cap, _key)
{
require(_cap < totalEtherCap);
// validate input
totalEtherCap = _cap;
}
/**
@dev computes the number of tokens that should be issued for a given contribution
@param _contribution contribution amount
@return computed number of tokens
*/
function computeReturn(uint128 _contribution) public constant returns (uint128) {
return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N;
}
/**
@dev ETH contribution
can only be called during the crowdsale
@return tokens issued in return
*/
function contributeETH()
public
payable
between(startTime, endTime)
returns (uint128 amount)
{
return processContribution();
}
/**
@dev Contribution through BTCs (Bitcoin Suisse only)
can only be called before the crowdsale started
@return tokens issued in return
*/
function contributeBTCs()
public
payable
btcsOnly
btcsEtherCapNotReached(uint128(msg.value))
earlierThan(startTime)
returns (uint128 amount)
{
return processContribution();
}
/**
@dev handles contribution logic
note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor
@return tokens issued in return
*/
function processContribution() private
active
etherCapNotReached(uint128(msg.value))
validGasPrice
returns (uint128 amount)
{
uint128 tokenAmount = computeReturn(uint128(msg.value));
beneficiary.transfer(uint128(msg.value));
// transfer the ether to the beneficiary account
totalEtherContributed = safeAdd(totalEtherContributed, uint128(msg.value));
// update the total contribution amount
token.issue(msg.sender, tokenAmount);
// issue new funds to the contributor in the smart token
token.issue(beneficiary, tokenAmount);
// issue tokens to the beneficiary
Contribution(msg.sender, uint128(msg.value), tokenAmount);
return tokenAmount;
}
// fallback
function() payable {
contributeETH();
}
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint128 public totalSupply = 0;
mapping(address => uint128) public balanceOf;
mapping(address => mapping(address => uint128)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint128 _value);
event Approval(address indexed _owner, address indexed _spender, uint128 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0);
// validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint128 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint128 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint128 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/*
Ether Token interface
*/
contract IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint128 _amount) public;
function withdrawTo(address _to, uint128 _amount);
}
/**
Ether tokenization contract
'Owned' is specified here for readability reasons
*/
contract EtherToken is IEtherToken, Owned, ERC20Token, TokenHolder {
// triggered when the total supply is increased
event Issuance(uint128 _amount);
// triggered when the total supply is decreased
event Destruction(uint128 _amount);
/**
@dev constructor
*/
function EtherToken()
ERC20Token('Ether Token', 'ETH', 8) {
}
/**
@dev deposit ether in the account
*/
function deposit() public payable {
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], uint128(msg.value));
// add the value to the account balance
totalSupply = safeAdd(totalSupply, uint128(msg.value));
// increase the total supply
Issuance(uint128(msg.value));
Transfer(this, msg.sender, uint128(msg.value));
}
/**
@dev withdraw ether from the account
@param _amount amount of ether to withdraw
*/
function withdraw(uint128 _amount) public {
withdrawTo(msg.sender, _amount);
}
/**
@dev withdraw ether from the account to a target account
@param _to account to receive the ether
@param _amount amount of ether to withdraw
*/
function withdrawTo(address _to, uint128 _amount)
public
notThis(_to)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount);
// deduct the amount from the account balance
totalSupply = safeSub(totalSupply, _amount);
// decrease the total supply
_to.transfer(_amount);
// send the amount to the target account
Transfer(msg.sender, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra protection
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint128 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint128 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transferFrom(_from, _to, _value));
return true;
}
/**
@dev deposit ether in the account
*/
function() public payable {
deposit();
}
}
contract TestERC20Token is ERC20Token {
function TestERC20Token(string _name, string _symbol, uint128 _supply)
public
ERC20Token(_name, _symbol, 0)
{
totalSupply = _supply;
balanceOf[msg.sender] = _supply;
}
}
/*
Smart Token v0.3
'Owned' is specified here for readability reasons
*/
contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
string public version = '0.3';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint128 _amount);
// triggered when the total supply is decreased
event Destruction(uint128 _amount);
/**
@dev constructor
@param _name token name
@param _symbol token short symbol, minimum 1 character
@param _decimals for display purposes only
*/
function SmartToken(string _name, string _symbol, uint8 _decimals)
ERC20Token(_name, _symbol, _decimals)
{
NewSmartToken(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
@dev disables/enables transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract owner
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint128 _amount)
public
//ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
Issuance(_amount);
Transfer(this, _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint128 _amount) public {
//require(msg.sender == _from || msg.sender == owner);
// validate input
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint128 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint128 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
|
/ get the full allowance amount transfer all tokens from the sender to the contract calculate ETH value of the tokens send the ETH amount to the seller
|
note that the function will sell the full allowance amount
@return ETH sent in return
function sell() public returns (uint128 amount) {
uint128 allowance = token.allowance(msg.sender, this);
assert(token.transferFrom(msg.sender, this, allowance));
uint128 etherValue = safeMul(allowance, TOKEN_PRICE_N) / TOKEN_PRICE_D;
msg.sender.transfer(etherValue);
return etherValue;
}
@param _amount amount of ETH to withdraw
| 2,545,981
|
pragma solidity ^ 0.5.8;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath
for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => bool) private authorizedCallers; // Addresses that can access this contract
// data structure to determine an airline
struct Airline {
address airlineAccount; // account address of airline
string name; // name of airline
bool isRegistered; // is this airline registered or not
bool isFunded; // is this airline funded or not
uint256 fund; // amount of fund available
}
// mapping to store airlines data
mapping(address => Airline) private airlines;
// number of airlines available
uint256 internal airlinesCount = 0;
// data structure to determine insurance
struct Insurance {
address payable insureeAccount; // account address of insuree
uint256 amount; // insurance amount
address airlineAccount; // account address of airline
string airlineName; // name of airline
uint256 timestamp; // timestamp of airline
}
// mapping to store insurances data
mapping(bytes32 => Insurance[]) private insurances;
// mapping to indicate flights whose payout have been credited
mapping(bytes32 => bool) private payoutCredited;
// mapping to store credits available for each insuree
mapping(address => uint256) private creditPayoutsToInsuree;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// event to trigger when airline gets registered
event AirlineRegistered(
address indexed airlineAccount, // account address of airline
string airlineName // name of airline
);
// event to trigger when airline gets funded
event AirlineFunded(
address indexed airlineAccount, // account address of airline
uint256 amount // amount funded to airline
);
// event to trigger when insurance is purchased
event InsurancePurchased(
address indexed insureeAccount, // account address of insuree
uint256 amount, // insurance amount
address airlineAccount, // account address of airline
string airlineName, // name of airline
uint256 timestamp // timestamp of airline
);
// event to trigger when insurance credit is available
event InsuranceCreditAvailable(
address indexed airlineAccount, // account address of airline
string indexed airlineName, // name of airline
uint256 indexed timestamp // timestamp of airline
);
// event to trigger when insurance is credited
event InsuranceCredited(
address indexed insureeAccount, // account address of insuree
uint256 amount // insurance amount
);
// event to trigger when insurance is paid
event InsurancePaid(
address indexed insureeAccount, // account address of insuree
uint256 amount // insurance amount
);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(
address _initialAirlineAccount,
string memory _initialAirlineName
)
public {
contractOwner = msg.sender;
addAirline(_initialAirlineAccount, _initialAirlineName);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the caller address either be registered as "authorized" or be the owner of the contract.
* This is used to avoid that other accounts may alter this data contract.
*/
modifier requireIsCallerAuthorized() {
require(authorizedCallers[msg.sender] == true || msg.sender == contractOwner, "Caller is not authorized");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires an airline account to be the function caller
*/
modifier requireIsAirline() {
require(airlines[msg.sender].isRegistered == true, "Caller is not airline");
_;
}
/**
* @dev Modifier that requires an airline account to be funded
*/
modifier requireIsAirlineFunded(address _airlineAccount) {
require(airlines[_airlineAccount].isFunded == true, "Airline is not funded");
_;
}
/**
* @dev Modifier that requires message data to be filled
*/
modifier requireMsgData() {
require(msg.data.length > 0, "Message data is empty");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add a new address to the list of authorized callers
* Can only be called by the contract owner
*/
function authorizeCaller(address contractAddress) external requireContractOwner {
authorizedCallers[contractAddress] = true;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
external
view
returns(bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(
bool mode
)
external
requireContractOwner {
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
address _airlineAccount,
string calldata _airlineName
)
external
requireIsCallerAuthorized {
addAirline(_airlineAccount, _airlineName);
}
function addAirline(
address _airlineAccount,
string memory _airlineName
)
private {
airlinesCount = airlinesCount.add(1);
airlines[_airlineAccount] = Airline(
_airlineAccount,
_airlineName,
true,
false,
0
);
emit AirlineRegistered(_airlineAccount, _airlineName);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address payable _insureeAccount,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
)
external
payable {
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(msg.value);
insurances[flightKey].push(
Insurance(
_insureeAccount,
msg.value,
_airlineAccount,
_airlineName,
_timestamp
)
);
emit InsurancePurchased(
_insureeAccount,
msg.value,
_airlineAccount,
_airlineName,
_timestamp
);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
uint256 _creditPercentage,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
) external
requireIsCallerAuthorized {
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
require(!payoutCredited[flightKey], "Insurance payout have already been credited");
for (uint i = 0; i < insurances[flightKey].length; i++) {
address insureeAccount = insurances[flightKey][i].insureeAccount;
uint256 amountToReceive = insurances[flightKey][i].amount.mul(_creditPercentage).div(100);
creditPayoutsToInsuree[insureeAccount] = creditPayoutsToInsuree[insureeAccount].add(amountToReceive);
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.sub(amountToReceive);
emit InsuranceCredited(insureeAccount, amountToReceive);
}
payoutCredited[flightKey] = true;
emit InsuranceCreditAvailable(_airlineAccount, _airlineName, _timestamp);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(
address payable _insureeAccount
)
external
requireIsCallerAuthorized {
uint256 payableAmount = creditPayoutsToInsuree[_insureeAccount];
delete(creditPayoutsToInsuree[_insureeAccount]);
_insureeAccount.transfer(payableAmount);
emit InsurancePaid(_insureeAccount, payableAmount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(
address _airlineAccount
)
external
payable
requireIsCallerAuthorized {
addFund(_airlineAccount, msg.value);
airlines[_airlineAccount].isFunded = true;
emit AirlineFunded(_airlineAccount, msg.value);
}
function addFund(
address _airlineAccount,
uint256 _fundValue
)
private {
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(_fundValue);
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev check if address is of airline or not
*
*/
function isAirline(
address _airlineAccount
)
external
view
returns(bool) {
return airlines[_airlineAccount].isRegistered == true;
}
/**
* @dev check if address is of airline or not
*
*/
function isAirlineFunded(
address _airlineAccount
)
external
view
requireIsCallerAuthorized
returns(bool) {
return airlines[_airlineAccount].isFunded == true;
}
/**
* @dev get fund of airline
*/
function getFund(
address _airlineAccount
) external
view
requireIsCallerAuthorized
returns(uint256) {
return airlines[_airlineAccount].fund;
}
/**
* @dev check if address is of airline or not
*
*/
function getAirlinesCount()
external
view
returns(uint256) {
return airlinesCount;
}
/**
* @dev get amount paid by insuree
*
*/
function getAmountPaidByInsuree(
address payable _insureeAccount,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
) external
view
returns(uint256 amountPaid) {
amountPaid = 0;
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
for (uint i = 0; i < insurances[flightKey].length; i++) {
if (insurances[flightKey][i].insureeAccount == _insureeAccount) {
amountPaid = insurances[flightKey][i].amount;
break;
}
}
}
/**
* @dev Returns insurees credits
*
*/
function getInsureePayoutCredits(
address payable _insureeAccount
) external
view
returns(uint256 amount) {
return creditPayoutsToInsuree[_insureeAccount];
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function ()
external
payable
requireMsgData
requireIsAirline {
addFund(msg.sender, msg.value);
airlines[msg.sender].isFunded = true;
emit AirlineFunded(msg.sender, msg.value);
}
}
|
check if address is of airline or not/
|
function isAirline(
address _airlineAccount
)
external
view
returns(bool) {
return airlines[_airlineAccount].isRegistered == true;
}
| 14,037,466
|
./full_match/80001/0x32E22c81f636C68cC3b6882E291e706fA4E96C1f/sources/contracts/member.sol
|
Function for a member to self-register with their details Make sure the member has inputted a registration ID from the admin Initialize the member's profile information
|
function registerSelf(
string memory _name,
string memory _phoneNumber,
string memory _image,
string memory _maritalStatus,
string memory _emailAddress,
string memory _houseAddress,
string memory _sex,
string memory _dateOfBirth,
string memory _validIdNumber
) external {
require(isAdminRegistered, "Please input a valid registration ID provided by the admin.");
memberProfile = MemberProfile(
_name,
_phoneNumber,
_image,
_maritalStatus,
_emailAddress,
_houseAddress,
_sex,
_dateOfBirth,
_validIdNumber
);
}
| 5,610,766
|
./partial_match/3/0xa269107FF4a5046CB07A48bB088b006Eae7E8f3C/sources/RecoverToken.sol
|
A method to add a stakeholder. _stakeholder The stakeholder to add./
|
function addStakeholder(address _stakeholder) public onlyOwner
{
(bool _isStakeholder, ) = isStakeholder(_stakeholder);
if(!_isStakeholder) stakeholders.push(_stakeholder);
}
| 5,119,265
|
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
pragma solidity 0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts\ERC865Basic.sol
/**
* @title ERC865Basic
* @dev Simpler version of the ERC865 interface from https://github.com/adilharis2001/ERC865Demo
* @author jsdavis28
* @notice ERC865Token allows for users to pay gas costs to a delegate in an ERC20 token
* https://github.com/ethereum/EIPs/issues/865
*/
contract ERC865Basic is ERC20 {
function _transferPreSigned(
bytes _signature,
address _from,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
internal;
event TransferPreSigned(
address indexed delegate,
address indexed from,
address indexed to,
uint256 value);
}
// File: openzeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\ERC865BasicToken.sol
/**
* @title ERC865BasicToken
* @dev Simpler version of the ERC865 token from https://github.com/adilharis2001/ERC865Demo
* @author jsdavis28
* @notice ERC865Token allows for users to pay gas costs to a delegate in an ERC20 token
* https://github.com/ethereum/EIPs/issues/865
*/
contract ERC865BasicToken is ERC865Basic, StandardToken {
/**
* @dev Sets internal variables for contract
*/
address internal feeAccount;
mapping(bytes => bool) internal signatures;
/**
* @dev Allows a delegate to submit a transaction on behalf of the token holder.
* @param _signature The signature, issued by the token holder.
* @param _to The recipient's address.
* @param _value The amount of tokens to be transferred.
* @param _fee The amount of tokens paid to the delegate for gas costs.
* @param _nonce The transaction number.
*/
function _transferPreSigned(
bytes _signature,
address _from,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
internal
{
//Pre-validate transaction
require(_to != address(0));
require(signatures[_signature] == false);
//Create a hash of the transaction details
bytes32 hashedTx = _transferPreSignedHashing(_to, _value, _fee, _nonce);
//Obtain the token holder's address and check balance
address from = _recover(hashedTx, _signature);
require(from == _from);
uint256 total = _value.add(_fee);
require(total <= balances[from]);
//Transfer tokens
balances[from] = balances[from].sub(_value).sub(_fee);
balances[_to] = balances[_to].add(_value);
balances[feeAccount] = balances[feeAccount].add(_fee);
//Mark transaction as completed
signatures[_signature] = true;
//TransferPreSigned ERC865 events
emit TransferPreSigned(msg.sender, from, _to, _value);
emit TransferPreSigned(msg.sender, from, feeAccount, _fee);
//Transfer ERC20 events
emit Transfer(from, _to, _value);
emit Transfer(from, feeAccount, _fee);
}
/**
* @dev Creates a hash of the transaction information passed to transferPresigned.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
* @return A copy of the hashed message signed by the token holder, with prefix added.
*/
function _transferPreSignedHashing(
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
internal pure
returns (bytes32)
{
//Create a copy of the hashed message signed by the token holder
bytes32 hash = keccak256(abi.encodePacked(_to, _value, _fee,_nonce));
//Add prefix to hash
return _prefix(hash);
}
/**
* @dev Adds prefix to the hashed message signed by the token holder.
* @param _hash The hashed message (keccak256) to be prefixed.
* @return Prefixed hashed message to return from _transferPreSignedHashing.
*/
function _prefix(bytes32 _hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash));
}
/**
* @dev Validate the transaction information and recover the token holder's address.
* @param _hash A prefixed version of the hash used in the original signed message.
* @param _sig The signature submitted by the token holder.
* @return The token holder/transaction signer's address.
*/
function _recover(bytes32 _hash, bytes _sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (_sig.length != 65) {
return (address(0));
}
//Split the signature into r, s and v variables
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
//Version of signature should be 27 or 28, but 0 and 1 are also possible
if (v < 27) {
v += 27;
}
//If the version is correct, return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(_hash, v, r, s);
}
}
}
// File: contracts\TaxedToken.sol
/**
* @title Taxed token
* @dev Version of BasicToken that allows for a fee on token transfers.
* See https://github.com/OpenZeppelin/openzeppelin-solidity/pull/788
* @author jsdavis28
*/
contract TaxedToken is ERC865BasicToken {
/**
* @dev Sets taxRate fee as public
*/
uint8 public taxRate;
/**
* @dev Transfer tokens to a specified account after diverting a fee to a central account.
* @param _to The receiving address.
* @param _value The number of tokens to transfer.
*/
function transfer(
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
uint256 fee = _value.mul(taxRate).div(100);
uint256 taxedValue = _value.sub(fee);
balances[_to] = balances[_to].add(taxedValue);
emit Transfer(msg.sender, _to, taxedValue);
balances[feeAccount] = balances[feeAccount].add(fee);
emit Transfer(msg.sender, feeAccount, fee);
return true;
}
/**
* @dev Provides a taxed transfer on StandardToken's transferFrom() function
* @param _from The address providing allowance to spend
* @param _to The receiving address.
* @param _value The number of tokens to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
uint256 fee = _value.mul(taxRate).div(100);
uint256 taxedValue = _value.sub(fee);
balances[_to] = balances[_to].add(taxedValue);
emit Transfer(_from, _to, taxedValue);
balances[feeAccount] = balances[feeAccount].add(fee);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, feeAccount, fee);
return true;
}
}
// File: openzeppelin-solidity\contracts\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts\Authorizable.sol
/**
* @title Authorizable
* @dev The Authorizable contract allows the owner to set a number of additional
* acccounts with limited administrative privileges to simplify user permissions.
* Only the contract owner can add or remove authorized accounts.
* @author jsdavis28
*/
contract Authorizable is Ownable {
using SafeMath for uint256;
address[] public authorized;
mapping(address => bool) internal authorizedIndex;
uint8 public numAuthorized;
/**
* @dev The Authorizable constructor sets the owner as authorized
*/
constructor() public {
authorized.length = 2;
authorized[1] = msg.sender;
authorizedIndex[msg.sender] = true;
numAuthorized = 1;
}
/**
* @dev Throws if called by any account other than an authorized account.
*/
modifier onlyAuthorized {
require(isAuthorized(msg.sender));
_;
}
/**
* @dev Allows the current owner to add an authorized account.
* @param _account The address being added as authorized.
*/
function addAuthorized(address _account) public onlyOwner {
if (authorizedIndex[_account] == false) {
authorizedIndex[_account] = true;
authorized.length++;
authorized[authorized.length.sub(1)] = _account;
numAuthorized++;
}
}
/**
* @dev Validates whether an account is authorized for enhanced permissions.
* @param _account The address being evaluated.
*/
function isAuthorized(address _account) public constant returns (bool) {
if (authorizedIndex[_account] == true) {
return true;
}
return false;
}
/**
* @dev Allows the current owner to remove an authorized account.
* @param _account The address to remove from authorized.
*/
function removeAuthorized(address _account) public onlyOwner {
require(isAuthorized(_account));
authorizedIndex[_account] = false;
numAuthorized--;
}
}
// File: contracts\BlockWRKToken.sol
/**
* @title BlockWRKToken
* @dev BlockWRKToken contains administrative features that allow the BlockWRK
* application to interface with the BlockWRK token, an ERC20-compliant token
* that integrates taxed token and ERC865 functionality.
* @author jsdavis28
*/
contract BlockWRKToken is TaxedToken, Authorizable {
/**
* @dev Sets token information.
*/
string public name = "BlockWRK";
string public symbol = "WRK";
uint8 public decimals = 4;
uint256 public INITIAL_SUPPLY;
/**
* @dev Sets public variables for BlockWRK token.
*/
address public distributionPoolWallet;
address public inAppPurchaseWallet;
address public reservedTokenWallet;
uint256 public premineDistributionPool;
uint256 public premineReserved;
/**
* @dev Sets private variables for custom token functions.
*/
uint256 internal decimalValue = 10000;
constructor() public {
feeAccount = 0xeCced56A201d1A6D1Da31A060868F96ACdba99B3;
distributionPoolWallet = 0xAB3Edd46E9D52e1b3131757e1Ed87FA885f48019;
inAppPurchaseWallet = 0x97eae8151487e054112E27D8c2eE5f17B3C6A83c;
reservedTokenWallet = 0xd6E4E287a4aE2E9d8BF7f0323f440acC0d5AD301;
premineDistributionPool = decimalValue.mul(5600000000);
premineReserved = decimalValue.mul(2000000000);
INITIAL_SUPPLY = premineDistributionPool.add(premineReserved);
balances[distributionPoolWallet] = premineDistributionPool;
emit Transfer(address(this), distributionPoolWallet, premineDistributionPool);
balances[reservedTokenWallet] = premineReserved;
emit Transfer(address(this), reservedTokenWallet, premineReserved);
totalSupply_ = INITIAL_SUPPLY;
taxRate = 2;
}
/**
* @dev Allows App to distribute WRK tokens to users.
* This function will be called by authorized from within the App.
* @param _to The recipient's BlockWRK address.
* @param _value The amount of WRK to transfer.
*/
function inAppTokenDistribution(
address _to,
uint256 _value
)
public
onlyAuthorized
{
require(_value <= balances[distributionPoolWallet]);
require(_to != address(0));
balances[distributionPoolWallet] = balances[distributionPoolWallet].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(distributionPoolWallet, _to, _value);
}
/**
* @dev Allows App to process fiat payments for WRK tokens, charging a fee in WRK.
* This function will be called by authorized from within the App.
* @param _to The buyer's BlockWRK address.
* @param _value The amount of WRK to transfer.
* @param _fee The fee charged in WRK for token purchase.
*/
function inAppTokenPurchase(
address _to,
uint256 _value,
uint256 _fee
)
public
onlyAuthorized
{
require(_value <= balances[inAppPurchaseWallet]);
require(_to != address(0));
balances[inAppPurchaseWallet] = balances[inAppPurchaseWallet].sub(_value);
uint256 netAmount = _value.sub(_fee);
balances[_to] = balances[_to].add(netAmount);
emit Transfer(inAppPurchaseWallet, _to, netAmount);
balances[feeAccount] = balances[feeAccount].add(_fee);
emit Transfer(inAppPurchaseWallet, feeAccount, _fee);
}
/**
* @dev Allows owner to set the percentage fee charged by TaxedToken on external transfers.
* @param _newRate The amount to be set.
*/
function setTaxRate(uint8 _newRate) public onlyOwner {
taxRate = _newRate;
}
/**
* @dev Allows owner to set the fee account to receive transfer fees.
* @param _newAddress The address to be set.
*/
function setFeeAccount(address _newAddress) public onlyOwner {
require(_newAddress != address(0));
feeAccount = _newAddress;
}
/**
* @dev Allows owner to set the wallet that holds WRK for sale via in-app purchases with fiat.
* @param _newAddress The address to be set.
*/
function setInAppPurchaseWallet(address _newAddress) public onlyOwner {
require(_newAddress != address(0));
inAppPurchaseWallet = _newAddress;
}
/**
* @dev Allows authorized to act as a delegate to transfer a pre-signed transaction for ERC865
* @param _signature The pre-signed message.
* @param _from The token sender.
* @param _to The token recipient.
* @param _value The amount of WRK to send the recipient.
* @param _fee The fee to be paid in WRK (calculated by App off-chain).
* @param _nonce The transaction number (stored in App off-chain).
*/
function transactionHandler(
bytes _signature,
address _from,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
onlyAuthorized
{
_transferPreSigned(_signature, _from, _to, _value, _fee, _nonce);
}
}
// File: contracts\BlockWRKICO.sol
/**
* @title BlockWRKICO
* @notice This contract manages the sale of WRK tokens for the BlockWRK ICO.
* @dev This contract incorporates elements of OpenZeppelin crowdsale contracts with some modifications.
* @author jsdavis28
*/
contract BlockWRKICO is BlockWRKToken {
/**
* @dev Sets public variables for BlockWRK ICO
*/
address public salesWallet;
uint256 public cap;
uint256 public closingTime;
uint256 public currentTierRate;
uint256 public openingTime;
uint256 public weiRaised;
/**
* @dev Sets private variables for custom token functions.
*/
uint256 internal availableInCurrentTier;
uint256 internal availableInSale;
uint256 internal totalPremineVolume;
uint256 internal totalSaleVolume;
uint256 internal totalTokenVolume;
uint256 internal tier1Rate;
uint256 internal tier2Rate;
uint256 internal tier3Rate;
uint256 internal tier4Rate;
uint256 internal tier5Rate;
uint256 internal tier6Rate;
uint256 internal tier7Rate;
uint256 internal tier8Rate;
uint256 internal tier9Rate;
uint256 internal tier10Rate;
uint256 internal tier1Volume;
uint256 internal tier2Volume;
uint256 internal tier3Volume;
uint256 internal tier4Volume;
uint256 internal tier5Volume;
uint256 internal tier6Volume;
uint256 internal tier7Volume;
uint256 internal tier8Volume;
uint256 internal tier9Volume;
uint256 internal tier10Volume;
constructor() public {
cap = 9999999999999999999999999999999999999999999999;
salesWallet = 0xA0E021fC3538ed52F9a3D79249ff1D3A67f91C42;
openingTime = 1557856800;
closingTime = 1589479200;
totalPremineVolume = 76000000000000;
totalSaleVolume = 43000000000000;
totalTokenVolume = 119000000000000;
availableInSale = totalSaleVolume;
tier1Rate = 100000;
tier2Rate = 10000;
tier3Rate = 2000;
tier4Rate = 1250;
tier5Rate = 625;
tier6Rate = 312;
tier7Rate = 156;
tier8Rate = 117;
tier9Rate = 104;
tier10Rate = 100;
tier1Volume = totalPremineVolume.add(1000000000000);
tier2Volume = tier1Volume.add(2000000000000);
tier3Volume = tier2Volume.add(5000000000000);
tier4Volume = tier3Volume.add(5000000000000);
tier5Volume = tier4Volume.add(5000000000000);
tier6Volume = tier5Volume.add(5000000000000);
tier7Volume = tier6Volume.add(5000000000000);
tier8Volume = tier7Volume.add(5000000000000);
tier9Volume = tier8Volume.add(5000000000000);
tier10Volume = tier9Volume.add(5000000000000);
}
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* Event marking the transfer of any remaining WRK to the distribution pool post-ICO
* @param wallet The address remaining sale tokens are delivered
* @param amount The remaining tokens after the sale has closed
*/
event CloseoutSale(address indexed wallet, uint256 amount);
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev Allows ICO participants to purchase WRK tokens
* @param _beneficiary The address of the ICO participant
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
//Calculate number of tokens to issue
uint256 tokens = _calculateTokens(weiAmount);
//Calculate new amount of Wei raised
weiRaised = weiRaised.add(weiAmount);
//Process token purchase and forward funcds to salesWallet
_processPurchase(_beneficiary, tokens);
_forwardFunds();
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Calculates total number of tokens to sell, accounting for varied rates per tier.
* @param _amountWei Total amount of Wei sent by ICO participant
* @return Total number of tokens to send to buyer
*/
function _calculateTokens(uint256 _amountWei) internal returns (uint256) {
//Tokens pending in sale
uint256 tokenAmountPending;
//Tokens to be sold
uint256 tokenAmountToIssue;
//Note: tierCaps must take into account reserved and distribution pool tokens
//Determine tokens remaining in tier and set current token rate
uint256 tokensRemainingInTier = _getRemainingTokens(totalSupply_);
//Calculate new tokens pending sale
uint256 newTokens = _getTokenAmount(_amountWei);
//Check if _newTokens exceeds _tokensRemainingInTier
bool nextTier = true;
while (nextTier) {
if (newTokens > tokensRemainingInTier) {
//Get tokens sold in current tier and add to pending total supply
tokenAmountPending = tokensRemainingInTier;
uint256 newTotal = totalSupply_.add(tokenAmountPending);
//Save number of tokens pending from current tier
tokenAmountToIssue = tokenAmountToIssue.add(tokenAmountPending);
//Calculate Wei spent in current tier and set remaining Wei for next tier
uint256 pendingAmountWei = tokenAmountPending.div(currentTierRate);
uint256 remainingWei = _amountWei.sub(pendingAmountWei);
//Calculate number of tokens in next tier
tokensRemainingInTier = _getRemainingTokens(newTotal);
newTokens = _getTokenAmount(remainingWei);
} else {
tokenAmountToIssue = tokenAmountToIssue.add(newTokens);
nextTier = false;
_setAvailableInCurrentTier(tokensRemainingInTier, newTokens);
_setAvailableInSale(newTokens);
}
}
//Return amount of tokens to be issued in this sale
return tokenAmountToIssue;
}
/**
* @dev Source of tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
totalSupply_ = totalSupply_.add(_tokenAmount);
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
salesWallet.transfer(msg.value);
}
/**
* @dev Performs a binary search of the sale tiers to determine current sales volume and rate.
* @param _tokensSold The total number of tokens sold in the ICO prior to this tx
* @return The remaining number of tokens for sale in the current sale tier
*/
function _getRemainingTokens(uint256 _tokensSold) internal returns (uint256) {
//Deteremine the current sale tier, set current rate and find remaining tokens in tier
uint256 remaining;
if (_tokensSold < tier5Volume) {
if (_tokensSold < tier3Volume) {
if (_tokensSold < tier1Volume) {
_setCurrentTierRate(tier1Rate);
remaining = tier1Volume.sub(_tokensSold);
} else if (_tokensSold < tier2Volume) {
_setCurrentTierRate(tier2Rate);
remaining = tier2Volume.sub(_tokensSold);
} else {
_setCurrentTierRate(tier3Rate);
remaining = tier3Volume.sub(_tokensSold);
}
} else {
if (_tokensSold < tier4Volume) {
_setCurrentTierRate(tier4Rate);
remaining = tier4Volume.sub(_tokensSold);
} else {
_setCurrentTierRate(tier5Rate);
remaining = tier5Volume.sub(_tokensSold);
}
}
} else {
if (_tokensSold < tier8Volume) {
if (_tokensSold < tier6Volume) {
_setCurrentTierRate(tier6Rate);
remaining = tier6Volume.sub(_tokensSold);
} else if (_tokensSold < tier7Volume) {
_setCurrentTierRate(tier7Rate);
remaining = tier7Volume.sub(_tokensSold);
} else {
_setCurrentTierRate(tier8Rate);
remaining = tier8Volume.sub(_tokensSold);
}
} else {
if (_tokensSold < tier9Volume) {
_setCurrentTierRate(tier9Rate);
remaining = tier9Volume.sub(_tokensSold);
} else {
_setCurrentTierRate(tier10Rate);
remaining = tier10Volume.sub(_tokensSold);
}
}
}
return remaining;
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(currentTierRate).mul(decimalValue).div(1 ether);
}
/**
* @dev Validation of an incoming purchase.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view {
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(weiRaised.add(_weiAmount) <= cap);
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Calculates remaining tokens available in the current tier after a sale is processed
* @param _tierPreviousRemaining Number of tokens remaining prior to sale
* @param _newIssue Number of tokens to be purchased
*/
function _setAvailableInCurrentTier(uint256 _tierPreviousRemaining, uint256 _newIssue) internal {
availableInCurrentTier = _tierPreviousRemaining.sub(_newIssue);
}
/**
* @dev Calculates remaining tokens available in the ICO after a sale is processed
* @param _newIssue Number of tokens to be purchased
*/
function _setAvailableInSale(uint256 _newIssue) internal {
availableInSale = totalSaleVolume.sub(_newIssue);
}
/**
* @dev Sets the current tier rate based on sale volume
* @param _rate The new rate
*/
function _setCurrentTierRate(uint256 _rate) internal {
currentTierRate = _rate;
}
/**
* @dev Returns the remaining number of tokens for sale
* @return Total remaining tokens available for sale
*/
function tokensRemainingInSale() public view returns (uint256) {
return availableInSale;
}
/**
* @dev Returns the remaining number of tokens for sale in the current tier
* @return Total remaining tokens available for sale in the current tier
*/
function tokensRemainingInTier() public view returns (uint256) {
return availableInCurrentTier;
}
/**
* @dev Allows the owner to transfer any remaining tokens not sold to a wallet
* @return Total remaining tokens available for sale
*/
function transferRemainingTokens() public onlyOwner {
//require that sale is closed
require(hasClosed());
//require that tokens are still remaining after close
require(availableInSale > 0);
//send remaining tokens to distribution pool wallet
balances[distributionPoolWallet] = balances[distributionPoolWallet].add(availableInSale);
emit CloseoutSale(distributionPoolWallet, availableInSale);
}
}
|
Allows the current owner to add an authorized account. _account The address being added as authorized./
|
function addAuthorized(address _account) public onlyOwner {
if (authorizedIndex[_account] == false) {
authorizedIndex[_account] = true;
authorized.length++;
authorized[authorized.length.sub(1)] = _account;
numAuthorized++;
}
}
| 15,854,263
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import "./Shop.sol";
contract ShopFactory {
mapping(bytes32=>address) private shopMapping;
string[] private names;
event ShopAdded(string name, address shopAddress);
constructor() public {
}
/// @dev validates name is between 1 and 40 characters
/// @dev 40 is a personal choice and could be something else
modifier nameIsCorrectLength(string memory shopName) {
bytes memory shopNameBytes = bytes(shopName);
require(shopNameBytes.length != 0 && shopNameBytes.length < 41);
_;
}
/// @dev validates the name does not already exist
modifier stringDoesNotExist(string memory shopName) {
bytes32 hashToCheck = keccak256(bytes(shopName));
require(address(shopMapping[hashToCheck]) == 0x0000000000000000000000000000000000000000);
_;
}
/// @notice Retrieves a list of all the shop names
/// @return shop names array
function getShops() public view returns (string[] memory) {
string[] memory safeNames = new string[](names.length);
for(uint i=0;i<names.length;i++) {
if(!isSafeString(names[i])) {
safeNames[i] = "***";
}
else {
safeNames[i] = names[i];
}
}
return safeNames;
}
/// @notice Retrieves the requested shop's address from its name
/// @param shopName the name of the shop
/// @return shopAddress - the address of the shop
/// @return shopHash - the hash of the shop name
function getShopLookupByName(string memory shopName) public view returns (address shopAddress,bytes32 shopHash) {
bytes32 shopHashed = keccak256(bytes(shopName));
shopAddress = address(shopMapping[shopHashed]);
shopHash = shopHashed;
}
/// @notice Retrieves the requested shop's address from its hash
/// @param shopHashed the hash of the shop name
/// @return shopAddress - the address of the shop
function getShopAddressByHash(bytes32 shopHashed) public view returns (address shopAddress) {
shopAddress = address(shopMapping[shopHashed]);
}
/// @notice Determine if the text is safe for use
/// @dev Each character is individually checked
/// @param str The string to interrogate
/// @return Boolean indicating if the text contains unexpected characters
function isSafeString(string memory str) private pure returns (bool ) {
bytes memory b = bytes(str);
for(uint i; i < b.length; i++) {
bytes1 char = b[i];
if( !(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x2E) && !(char == 0x20) // ." "
)
return false;
}
return true;
}
function AddShopInstance(string memory shopName)
nameIsCorrectLength(shopName)
stringDoesNotExist(shopName)
public
{
require(names.length < 50," There are already 50 shops");
bytes32 shopHashed = keccak256(bytes(shopName));
Shop newShop = new Shop(msg.sender);
names.push(shopName);
shopMapping[shopHashed] = address(newShop);
emit ShopAdded(shopName,address(newShop));
}
}
|
Determine if the text is safe for use Each character is individually checked str The string to interrogate return Boolean indicating if the text contains unexpected characters
|
function isSafeString(string memory str) private pure returns (bool ) {
bytes memory b = bytes(str);
for(uint i; i < b.length; i++) {
bytes1 char = b[i];
)
return false;
}
return true;
}
| 1,757,834
|
./partial_match/56/0x820F1716e605d8D8DD6cdF872eb2Eb49C17351d0/sources/TajToken.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TAJ::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,074,752
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.